【问题标题】:Python & Numpy - Finding the Mode of Values in an Array that aren't ZeroPython & Numpy - 查找数组中非零值的模式
【发布时间】:2020-04-28 18:43:37
【问题描述】:

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

我已经屏蔽了其中的一部分(将这些值设为 0),现在我想在我的非屏蔽区域中找到值的模式。

我遇到的问题是模式命令不断返回 [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 中的“面部”的完整代码 - 该图像仍然看起来很慢,结果是“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)

【问题讨论】:

  • 在参数中尝试 mR[mask]
  • 除非我遗漏了什么,你不能用掩码只选择你想要的值/元素吗?
  • 完整输出是什么?
  • 请发布您的完整代码
  • @jtlz2 - 上面发布的完整代码 - 使用来自 scipy 的“面部”图像,它仍然运行缓慢并且给了我错误的值(似乎忽略了掩码)。

标签: python numpy image-processing


【解决方案1】:

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

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

# mode
modeR = np.argmax(counts)

【讨论】:

  • 更简单的方法是unique, counts = np.unique(a[a>0], return_counts=True) np.argmax(counts)
【解决方案2】:

更新:

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

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

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

我的旧答案:

试试

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

除了掩码,有效地计算一个 numpy 数组的模式在这里被广泛地介绍:

Most efficient way to find mode in numpy array

【讨论】:

  • 是的,添加 [mask] 有效 - 但运行速度非常慢。并注意到它没有给我一个有效的值(显示为 233),无论我的掩码是什么,当值应该很慢(20 或 30 秒)时......似乎它不尊重掩码。
  • 你是如何生成你的面具的?数组维度是多少
猜你喜欢
  • 2014-06-08
  • 1970-01-01
  • 2019-06-27
  • 1970-01-01
  • 2017-01-02
  • 1970-01-01
  • 2017-07-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多