Python 和 Numpy - 查找数组中非零值的模式



我有一个Numpy数组(它是图像中的红色通道(。

我已经屏蔽了它的一部分(使这些值为0(,现在我想在我的非屏蔽区域中找到值的Mode。

我遇到的问题是Mode命令不断返回[0]。我想排除0值(遮罩区域(,但我不确定如何做到这一点?

这是我用来尝试获取模式的命令:

#mR is the Numpy Array of the Red channel with the values of the areas I don't want at 0

print(stats.mode(mR[:, :], axis=None))

返回0作为我的模式。如何排除0或遮罩区域?

更新-完整代码:

这是我使用scipy.misc中的"face"的完整代码-对该图像来说仍然很慢,结果是"107",这对于遮罩区域(阴影(来说太高了,所以它似乎在处理整个图像,而不仅仅是遮罩中的区域。


import cv2
import numpy as np
from scipy import stats
import scipy.misc

img = scipy.misc.face()
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
r, g, b = cv2.split(img_rgb)

img_lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
l_channel ,a_channel, b_channel = cv2.split(img_lab)

mask = cv2.inRange(l_channel, 5, 10)
cv2.imshow("mask", mask)

print(stats.mode(r[mask],axis=None))

cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)

您可以只屏蔽数组并使用np.histogram:

counts, bins = np.histogram(mR[mR>0], bins=np.arange(256))
# mode
modeR = np.argmax(counts)

更新:

在OP善意地发布了他们的完整代码后,我可以确认stats.mode()要么非常慢,要么实际上从未完成(谁知道为什么?(。

另一方面,@Quang Hoang的解决方案既优雅又快速,在尊重口罩方面也对我有效。

因此,我当然支持QH的回答。

我的老答案:

尝试

print(stats.mode(mR[mask],axis=None))

除了掩蔽之外,这里广泛讨论了有效计算numpy阵列的模式:

在numpy阵列中查找模式的最有效方法