请注意,我已经阅读了同一期问题的答案,但没有人跟我一样。
我在OpenCV中加载了一张图片并显示出来。一切都很好。
现在我想将黑色像素设置为蓝色,所以我运行:
for i in range(image.shape[0]):
for j in range(image.shape[1]):
if image[i,j,0]==0 and image[i,j,1]==0 and image[i,j,2]==0:
image[i,j,0]=255
我遇到了这个错误:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
注意事项:
符号
image[i,j,0]
,image[i,j,1]
和image[i,j,2]
在像素的 channel 值(BGR = Blue Green Red)下划线,因此它不是此错误消息所说的数组。如果 Python 不理解自己,那就太奇怪了。当我运行
print image[i,j,x]
, 与x
=0,1,2 我得到随机值i
的正常行为和j
.也就是说,我正确地获得了这 3 个 channel 的值。
最佳答案
试试这个:
import numpy as np
image[np.all(image == 0, axis=-1)] = [255, 0, 0]
此处使用numpy操作仅检查Z轴,并将其替换为像素 channel 均为0的蓝色。 它的速度要快得多(至少对于大图像而言)并且也不那么曲折。
关于python - ValueError : The truth value of an array with more than one element is ambiguous. 使用 a.any() 或 a.all(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28900602/