首页 > 解决方案 > 获取数组中子数组的轮廓索引

问题描述

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]])

零定义了一个形状:

在此处输入图像描述

我的问题是:如何提取定义形状轮廓的零点的索引?

在此处输入图像描述

标签: pythonlistnumpy

解决方案


如果您不介意使用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]])

推荐阅读