简体   繁体   English

获取数组中子数组的轮廓索引

[英]Get contour indexes of subarray in array

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

The zeros define a shape:零定义了一个形状:

在此处输入图像描述

My question is: How can I extract the indexes of the zeros which define the contour of the shape?我的问题是:如何提取定义形状轮廓的零点的索引?

在此处输入图像描述

If you don't mind using scipy , you can use a 2D convolution to check if your zero values are surrounded by other zero values or not:如果您不介意使用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.

and we obtain the following boolean index:我们得到以下 boolean 索引:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM