简体   繁体   English

尝试仅显示所捕获图像的某些彩色像素时出错

[英]Error while trying to display only certain colour pixels of an image that is captured

I am trying to convert all the pixels of a captured image, that are not in the color yellow to white. 我正在尝试将捕获图像的所有像素(不是黄色)转换为白色。

The error message that I am getting is: 我收到的错误消息是:

if jmg[i,j]!=[255,255,0]:
valueError: the truth value of an array with more than one element is ambiguous. use a.any() or a.all()

Below is my code: 下面是我的代码:

import cv2
import picamera
import numpy
import time
from matplotlib import pyplot as plt
print("ready")
with picamera.PiCamera() as camera:
    camera.resolution=(400,400)
    time.sleep(1)
    camera.capture("/home/pi/rowdy.jpg")
    print("Done")
yellow=[255,255,0]
img=cv2.imread("/home/pi/rowdy.jpg",1)
jmg=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
for i in numpy.arange(399):
  for j in numpy.arange(399):
      if jmg[i,j]!=[255,255,0]:
          jmg[i,j]=[255,255,255]

plt.imshow(jmg)
plt.xticks([]),plt.yticks([])
plt.show()

jmg is a numpy array of three values. jmg是一个由三个值组成的numpy数组。 When you compare a numpy array to another array (or list, in your case), it will compare them element-wise . 当您将numpy数组与另一个数组(或列表)进行比较时,它将按element-wise进行比较。

if jmg[i,j]!=[255,255,0]: #np.array(255, 0, 0) != [255,255,0]
                          # -> np.array(False, True, False)

This means that you need to do what the error message says and use either any() or all() to determine the value you want. 这意味着您需要执行错误消息中所说的操作,并使用any()all()来确定所需的值。 In your case, you want to check if any of those values don't match, which means your element-wise logic would make one of the three values True 在你的情况,你要检查,如果any这些值不匹配,这意味着你的元素智能逻辑将使这三个值中的一个True

if (jmg[i,j]!=[255,255,0]).any():
          jmg[i,j]=[255,255,255]

A much faster way is to use the numpy library. 一种更快的方法是使用numpy库。 First create a copy of the mage and then using numpy.argwhere replace the pixel values at the required positions: 首先创建法师的副本,然后使用numpy.argwhere在所需位置替换像素值:

image1 = image.copy()
image1[np.argwhere(image != [255,255,0])] = [255,255,255]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM