Search code examples
numpymatplotlibopencvvalueerrorpython

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() in plt.show() while plotting frame


I am trying to capture a video frame and then plot it using plt.imshow() but i am receiving this error.

vs = cv2.VideoCapture('../input/hard-hat-dataset/short_clip.mp`enter code here`4')
(grabbed, img) = vs.read()

img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.show(img)

Error :

ValueError                               Traceback (most recent call last)
<ipython-input-49-1e7d2b5de2de> in <module>
3 
4 img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
5 plt.show(img)
6 
7 

/opt/conda/lib/python3.7/site-packages/matplotlib/pyplot.py in show(*args, **kwargs)
376     """
377     _warn_if_gui_out_of_main_thread()
378     return _backend_mod.show(*args, **kwargs)
379 
380 

/opt/conda/lib/python3.7**/site-packages/matplotlib_inline/backend_inline.py in show(close, 
block)
47         # only call close('all') if any to close
48         # close triggers gc.collect, which can be 
49         if close and Gcf.get_all_fig_managers():
50             matplotlib.pyplot.close('all')
51 
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() 
or a.all()

If i print the image it is in numpy format of right size.*

vs = cv2.VideoCapture('../input/hard-hat-dataset/short_clip.mp4')
(grabbed, img) = vs.read()

img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
print(img)

[[[107 107 104]
[173 175 175]
[107 107 104]
....
[173 175 175]
[173 175 175]]

Solution

  • The function plt.show is for showing the final matplotlib figure. You can't pass data into this. So use plt.imshow first to generate a figure that contains the image and show it with plt.show.

    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    
    plt.imshow(img)
    plt.show()