Capturing and processing video from a webcam
We will use a webcam in this chapter to capture video data. Let's see how to capture the video from the webcam using OpenCV-Python.
How to do it…
Create a new Python file, and import the following packages:
import cv2
OpenCV provides a video capture object that we can use to capture images from the webcam. The
0
input argument specifies the ID of the webcam. If you connect a USB camera, then it will have a different ID:# Initialize video capture object cap = cv2.VideoCapture(0)
Define the scaling factor for the frames captured using the webcam:
# Define the image size scaling factor scaling_factor = 0.5
Start an infinite loop and keep capturing frames until you press the Esc key. Read the frame from the webcam:
# Loop until you hit the Esc key while True: # Capture the current frame ret, frame = cap.read()
Resizing the frame is optional but still a useful thing to have in your code:
# Resize the frame frame = cv2.resize(frame, None, fx=scaling_factor...