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:
    # Loop until you hit the Esc key
    while True:
        # Capture the current frame
        ret, frame = cap.read()
  5. 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, fy=scaling_factor, 
                interpolation=cv2.INTER_AREA)
  6. Display the frame:
        # Display the image
        cv2.imshow('Webcam', frame)
  7. Wait for 1 ms before capturing the next frame:
        # Detect if the Esc key has been pressed
        c = cv2.waitKey(1)
        if c == 27:
            break
  8. Release the video capture object:
    # Release the video capture object
    cap.release()
  9. Close all active windows before exiting the code:
    # Close all active windows
    cv2.destroyAllWindows()
  10. The full code is given in the video_capture.py file that's already provided to you for reference. If you run this code, you will see the video from the webcam, similar to the following screenshot:
    How to do it…
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.17.46