Accessing camera modules from the OpenCV library
In the previous section, we used a still image as a source for the OpenCV library. We can use a camera as the source of a still image. A camera generates video data, which is a collection of still images. To access camera modules from the OpenCV library, follow these steps:
To access a camera from OpenCV, we can use the
VideoCapture
object. We callread()
to read a frame, which is a still of a frame.For a demo, we use the camera USB drive. Just connect this device to the Raspberry Pi board through the USB drive. Then, we write the following scripts with your text editor:
import numpy as np import cv2 cap = cv2.VideoCapture(0) while True: # Capture frame-by-frame ret, frame = cap.read() # Display the resulting frame cv2.imshow('video player', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
Save these scripts into a file, called
ch03_camera_player.py
.To run this program...