I’m trying to use code from the official openCV tutorial for showing video from webcam using cv2.imshow()
in Ubuntu/Python 3.6:
import numpy as np import cv2 cap = cv2.VideoCapture(0) while(True): # Capture frame-by-frame ret, frame = cap.read() # Our operations on the frame come here gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Display the resulting frame cv2.imshow('frame',gray) if cv2.waitKey(1) & 0xFF == ord('q'): break # When everything done, release the capture cap.release() cv2.destroyAllWindows()
And I get the following error for cv2.imshow()
:
The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Carbon support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script in function cvShowImage
When searching for the error I stumbled upon this post as an alternate answer to similar questions:
If you installed OpenCV using the opencv-python pip package at any point in time, be aware of the following note, taken from https://pypi.python.org/pypi/opencv-python
IMPORTANT NOTE MacOS and Linux wheels have currently some limitations:
- video related functionality is not supported (not compiled with FFmpeg)
- for example cv2.imshow() will not work (not compiled with GTK+ 2.x or Carbon support)
Also note that to install from another source, first you must remove the opencv-python package
OpenCV error: the function is not implemented
Most other openCV functions work properly.
Is there an alternative to cv2.imshow()
that uses standard anaconda libraries so I don’t have to recompile openCV or use Python 2.7?
Advertisement
Answer
I hacked together a quick and dirty snippet that uses matplotlib.animation
and resembles what cv2.imshow() is expected to do with webcam video:
import cv2 import matplotlib.pyplot as plt import matplotlib.animation as animation cap = cv2.VideoCapture(0) ret, frame = cap.read() # The following is the replacement for cv2.imshow(): fig = plt.figure() ax = fig.add_subplot(111) im = ax.imshow(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB), animated=True) def updatefig(*args): ret, frame = cap.read() im.set_array(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) return im ani = animation.FuncAnimation(fig, updatefig, interval=10) plt.show()
I found this very useful, as I was able to output many overlapping plots on top of the webcam video thanks to the fact that matplotlib.animation.FuncAnimation
can animate as many plots as there are attached to the ax
object as long as they are updated in the updatefig()
function above.
Edit: As I was working in a Jupyter notebook, I added the following in order to see the video in a new window:
import matplotlib matplotlib.use('qt5agg')