python - ValueError : The truth value of an array with more than one element is ambiguous. 使用 a.any() 或 a.all()

标签 python opencv numpy

请注意,我已经阅读了同一期问题的答案,但没有人跟我一样。

我在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/

相关文章:

python - 将 ctypes 结构传递给 cython

python - 这有可能吗?从一个python shell发送命令/对象到另一个?

python - 使用 Python 自然语言工具包阅读孟加拉语

c++ - opencv中基于ROI的KLT光学跟踪器

python - np.from函数 : Reference other arrays

python - Optparse 和很多 if not

Python3 在网络摄像头 fps 处处理和显示网络摄像头流

c++ - 如何在 MFC View 上显示 OpenCV Mat

python查找列表中数组的索引

python - 为坐标 x 和 y 列表找到优化位置