[英]How to find the number of neighbours pixels in binary array
您可以使用邊緣檢測內核來解決這個問題。
import numpy as np
from scipy.ndimage import convolve
a = np.array([[0, 0, 0, 0],
[0, 1, 1, 1],
[0, 1, 1, 1]])
kernel = np.array([[-1, -1, -1],
[-1, 8, -1],
[-1, -1, -1]])
然后,我們將原始數組與內核進行卷積。 請注意,邊緣都是負的。
>>> convolve(a, kernel)
[[-1 -2 -3 -3]
[-2 5 3 3]
[-3 3 0 0]]
我們將計算負值的數量並得到結果。
>>> np.where(convolve(a, kernel) < 0, 1, 0)
[[1 1 1 1]
[1 0 0 0]
[1 0 0 0]]
>>> np.sum(np.where(convolve(a, kernel) < 0, 1, 0))
6
你可以用內核做很多事情。 例如,如果您不想包含對角線鄰居,則可以修改內核。
kernel = np.array([[ 0, -1, 0],
[-1, 4, -1],
[ 0, -1, 0]])
這給出了以下輸出。
>>> np.where(convolve(a, kernel) < 0, 1, 0)
[[0 1 1 1]
[1 0 0 0]
[1 0 0 0]]
>>> np.sum(np.where(convolve(a, kernel) < 0, 1, 0))
5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.