具有超过1个比较的布尔矩阵引发错误“具有多个元素的数组的真值不明确”

时间:2019-08-08 23:26:17

标签: python numpy opencv pixel boolean-logic

我正在尝试查找像素的HSV值是否在正确的阈值之内,但是会引发错误:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我想做的是:

x, y = numpy.where(0.08196969696969696 >= img >= 0.1 and 0.7285714285714286 >= img >= 0.525 and 150 >= img >= 95)

如何在numpy数组中找到该阈值内的所有可能像素?

1 个答案:

答案 0 :(得分:0)

x, y = numpy.where(0.08196969696969696 >= img >= 0.1 and 0.7285714285714286 >= img >= 0.525 and 150 >= img >= 95)

关注参数,该参数应生成一个n维布尔数组:

0.08196969696969696 >= img >= 0.1 and 0.7285714285714286 >= img >= 0.525 and 150 >= img >= 95)

()和&:

(0.08196969696969696 >= img >= 0.1) & (0.7285714285714286 >= img >= 0.525) & (150 >= img >= 95)

双面比较仅适用于python标量,不适用于numpy:

(0.08196969696969696 >= img) & (img >= 0.1) & (0.7285714285714286 >= img) & (img >= 0.525) & (150 >= img) & (img >= 95)

https://docs.scipy.org/doc/numpy-1.9.3/reference/routines.logic.html

np.logical_and.reduce(((0.08196969696969696 >= img), (img >= 0.1), (0.7285714285714286 >= img), (img >= 0.525), (150 >= img), (img >= 95)))

但是等等,我们不能仅仅将所有这些测试减少到2个吗? img的形状是什么?最终尺寸为3维的3d会是偶然的吗?

np.logical_and.reduce(((0.08196969696969696 >= img[:,:,0]), (img[:,:,0] >= 0.1), 
(0.7285714285714286 >= img[:,:,1]), (img[:,:,1] >= 0.525), 
(150 >= img[:,:,2]), (img[:,:,2] >= 95)))

或比较(n,m,3)img与(3,)边界,并在最后一个轴上减少all

([0.08196969696969696, 0.7285714285714286, 150] >= img).all(axis=2) & 
([0.1, 0.525, 95] >= img).all(axis=2)