banner image

Real-Time Webcam Capture in Python Using OpenCV

    Capturing real-time video from a webcam is a foundational skill in many computer vision and machine learning projects. Whether you're building a face detection system, a motion tracker, or a gesture-controlled app, accessing your webcam using Python and OpenCV is often the first step. In this tutorial, we’ll walk through how to open your webcam, display the live video feed, and exit the program safely. Let’s dive into the code and get started!


    In this section, we import the OpenCV library and initialize the webcam using cv2.VideoCapture(0). This allows us to capture live video input from the default camera source.


# Import the OpenCV library
import cv2

# Initialize the webcam (0 is the default camera)
capture = cv2.VideoCapture(0)
  

    This loop reads video frames from the webcam in real time and displays them in a separate window. If a frame fails to load, the program continues to the next one without crashing. At the end of each loop we also check if the 'e' key was pressed to exit the video stream.


# Start an infinite loop to read video frames continuously
while True:
    # Read a single frame from the webcam
    re, frame = capture.read()

    # If frame is not received correctly, skip to the next iteration
    if not re:
        continue

    # Display the current video frame in a window titled 'frame'
    cv2.imshow("frame", frame)
    # Wait for 1 millisecond and check if the 'e' key is pressed
    if cv2.waitKey(1) & 0xFF == ord('e'):
        break
  

    In this final step, we release the webcam and close all OpenCV windows properly to free system resources.



# Release the webcam after exiting the loop
capture.release()

# Close all OpenCV windows to clean up
cv2.destroyAllWindows()
  
Real-Time Webcam Capture in Python Using OpenCV Real-Time Webcam Capture in Python Using OpenCV Reviewed by Can Ozgan on June 16, 2025 Rating: 5

No comments:

Powered by Blogger.