Real-time video display using OpenCV
Before we move on to face detection, let's first see whether we can access our camera or not. To do that, let's write a very simple Python script to display the webcam video feed:
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()
In the preceding code, we initially import the openCV module as import cv2
.
Next we initialize the video capture device and set the index to zero as we're using the default webcam that comes with the laptop. For desktop users, you may need to vary the parameter.
After the initialization, in an infinite loop, we read the incoming video frame by frame using cap.read...