python - 获取数组中子数组的轮廓索引
问题描述
array = np.array([\
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 255],
[ 0, 0, 0, 0, 0, 0, 0, 255, 255, 255],
[ 0, 0, 0, 0, 0, 255, 255, 255, 255, 255],
[ 0, 0, 0, 255, 255, 255, 255, 255, 255, 255],
[ 0, 255, 255, 255, 255, 255, 255, 255, 255, 255]])
零定义了一个形状:
我的问题是:如何提取定义形状轮廓的零点的索引?
解决方案
如果您不介意使用scipy
,您可以使用 2D 卷积来检查您的零值是否被其他零值包围:
import numpy as np
import scipy.signal as signal
# Dummy input
A = np.array([[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 255],
[ 0, 0, 0, 0, 0, 0, 0, 255, 255, 255],
[ 0, 0, 0, 0, 0, 255, 255, 255, 255, 255],
[ 0, 0, 0, 255, 255, 255, 255, 255, 255, 255],
[ 0, 255, 255, 255, 255, 255, 255, 255, 255, 255]])
# We convolve the array with a 3x3 kernel filled with one,
# we use mode='same' in order to preserve the shape of the original array
# and we multiply the result by (A==0).
c2d = signal.convolve2d(A==0,np.ones((3,3)),mode='same')*(A==0)
# It is on the border if the values are > 0 and not equal to 9 so:
res = ((c2d>0) & (c2d<9)).astype(int)
# use np.where(res) if you need a linear index instead.
我们得到以下布尔索引:
array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[1, 0, 0, 0, 1, 1, 1, 0, 0, 0],
[1, 0, 1, 1, 1, 0, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
推荐阅读
- c# - Enable-Migrations - 无法将参数绑定到参数“路径”
- javascript - 如何在 ReactJS 中创建一个包含所有验证和错误处理的通用文本框?
- azure-devops - 将 Azure CLI 任务的结果存储到发布变量中
- android - 应用程序运行时不起作用 - 权限错误
- java - 无法获得输出“用户名已被使用!” 当我输入已存储在数据库中的用户名时
- c++ - C++ 使用未声明的标识符
- javafx - 如何在按钮中创建复选框?(javafx)
- android - 如何解决在 android studio 中找不到应用程序的问题?
- javascript - 选项卡内容与其他选项卡内容重叠
- php - 如果用户 ID 在 foreach 循环 laravel 中相同,则合并表行