我正在寻找一种简单的方法来计算下图中绿色像素的数量,其中原始图像是相同的,但绿色像素是黑色的。
\n我用 尝试过numpy.diff(),但后来我对一些像素进行了两次计数。我想过numpy.gradient()\xe2\x80\x93 但在这里我不确定它是否是正确的工具。
我知道这个问题必须有很多解决方案,但我不知道如何用谷歌搜索它。我正在寻找 python 中的解决方案。
\n\n为了更清楚地说明,我只有一张图像(只有黑白像素)。带有绿色像素的图像仅供参考。
\n您可以使用边缘检测内核来解决此问题。
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]])
Run Code Online (Sandbox Code Playgroud)
然后,我们将原始数组与内核进行卷积。请注意,边缘都是负片。
>>> convolve(a, kernel)
[[-1 -2 -3 -3]
[-2 5 3 3]
[-3 3 0 0]]
Run Code Online (Sandbox Code Playgroud)
我们将计算负值的数量并得到结果。
>>> 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
Run Code Online (Sandbox Code Playgroud)
您可以使用内核做很多事情。例如,如果您不想包含对角邻居,则可以修改内核。
kernel = np.array([[ 0, -1, 0],
[-1, 4, -1],
[ 0, -1, 0]])
Run Code Online (Sandbox Code Playgroud)
这给出了以下输出。
>>> 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
900 次 |
| 最近记录: |