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…

  1. Create a new Python file, and import the following packages:
    import cv2
  2. 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)
  3. Define the scaling factor for the frames captured using the webcam:
    # Define the image size scaling factor
    scaling_factor = 0.5
  4. Start an infinite loop and keep capturing frames until you press the Esc key. Read the frame from the webcam: ...

Get Python Machine Learning Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.