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

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

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

我在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()

诺塔贝内:

试试这个:

import numpy as np

image[np.all(image == 0, axis=-1)] = [255, 0, 0]

这里用numpy操作只勾选Z轴,替换为像素通道全为0的蓝色。 它的速度无限快(至少对于大图像而言)并且不那么曲折。