使用Scipy基于邻近性组合阵列

oyxsuwqo  于 2022-11-10  发布在  其他
关注(0)|答案(1)|浏览(138)

这里我的目标是合并那些元素与其他数组的距离小于3个像素的数组。下面是我使用的代码:

import numpy as np, matplotlib.pyplot as plt
from scipy.signal import convolve2d
from scipy.ndimage import label 

## Example matrix

arr = np.array([[0,0,0,0,0,0,0,0,0,0,0,0],
                [0,0,1,0,0,0,0,0,0,0,0,0],
                [0,0,1,0,0,0,0,0,0,0,0,0],
                [0,0,0,1,0,0,0,0,0,0,0,0],
                [0,0,1,0,0,0,0,1,0,0,0,0],
                [0,0,0,0,0,0,0,0,1,0,0,0],
                [0,0,1,0,0,0,0,0,0,1,0,0],
                [0,0,1,0,0,0,0,0,1,1,0,0],
                [0,0,0,1,0,0,0,0,1,0,0,0],
                [0,0,0,1,0,0,0,0,0,0,0,0],
                [0,0,0,0,0,0,0,0,0,0,0,0],
                [0,0,0,0,0,0,0,0,0,0,0,0],
                [0,0,0,0,0,0,0,0,0,0,0,0]])

## Check if neighboring cells are zero using a 2d convolution:

# The kernel

ker = np.array([[1,1,1],
                [1,0,1],
                [1,1,1]])
ker2= np.array([[1,1,1],
                [1,1,1],
                [1,1,1]])
res = convolve2d(arr,ker,mode='same')

# Eliminate the noise

res = np.int32((res>0)&(arr>0))

# Using label your can segment an image and since an image is basically a matrix:

lab = label(res, ker2)
print(lab)

# Get the coordinate of each line.

coord = []
for ii in range(lab[1]):
    coord.append(np.vstack(np.where(lab[0]==(ii+1))))

for i, e in enumerate(coord):
    xVals = e[1]
    yVals = e[0]
    plt.scatter(xVals, yVals)

plt.xlim(0,len(arr[0]))
plt.ylim(0,len(arr))
plt.yticks(np.linspace(0,len(arr), len(arr)+1))
plt.grid()
plt.show()

这将返回:

请注意,蓝色、绿色和橙子数据点(像素)是独立的数组。我想合并蓝色和绿色数组(相距1个像素),而保留橙色数组(相距〉2个像素)。这里分配给变量“arr”的数组只是示例数据。真实的数据将来自一个大的图像文件,因此该问题的解决方案必须足够有效,以便在更大的范围内实用。
谢谢你的帮助。

hivapdat

hivapdat1#

您可以使用您的算法,只需稍作更改:
首先将每个像素增大一个像素:

(n,m) = arr.shape
arr_out =  np.zeros((n+2,m+2))
for i in range(n):
    for j in range(m):
        if arr[i,j] == 1:
            for k in range(3):
                for l in range(3):
                    arr_out[i+k][j+l] = 1
arr_out = arr_out[1:-1,1:-1]

接下来,使用新图像运行算法:arr_out(终止)
然后,您可以使用arr作为lab上的掩码:

lab[0][arr<1] = 0

给予:

除了编写自己的循环,您还可以使用skimage中的以下例程:

from skimage.morphology import square, dilation
dilation(arr, square(3))

相关问题