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

Clash Royale CLAN TAG#URR8PPP
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()
2 Answers
2
jmg is a numpy array of three values. When you compare a numpy array to another array (or list, in your case), it will compare them element-wise.
jmg
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. 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()
all()
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. First create a copy of the mage and then using numpy.argwhere replace the pixel values at the required positions:
numpy
numpy.argwhere
image1 = image.copy()
image1[np.argwhere(image != [255,255,0])] = [255,255,255]
Thanks ,I will try it.
– user42095
Aug 6 at 15:56
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
You can use the numpy library for speeding up the operation. Have a look at the answer!
– Jeru Luke
Aug 6 at 15:54