Adam Hacks

Python - How to Capture Video from a Webcam with OpenCV

Have you ever written code to interface with a webcam? Well, if you have then you know that it can be a royal pain in the ass. And God forbid you want it to be a cross-platform solution! The good news is that there is a ready-made solution that can help us out: OpenCV. Yes, you heard me right. Not only is OpenCV and amazing computer vision library, but it also provides a handy, cross-platform way of interfacing with webcams. Let’s take a look at how simple OpenCV makes this. I’ll be using Python for these examples, but the API is similar in other languages.

Shut Up and Show me the Code!

Okay, okay, we’ll take a look at the code already :)

 1import cv2
 2# Open a handle to the default webcam
 3camera = cv2.VideoCapture(0)
 4# Start the capture loop
 5while True:
 6    # Get a frame
 7    ret_val, frame = camera.read()
 8    # Show the frame
 9    cv2.imshow('Webcam Video Feed', frame)
10    # Stop the capture by hitting the 'esc' key
11    if cv2.waitKey(1) == 27:
12        break
13# Dispose of all open windows
14cv2.destroyAllWindows()

Not too surprisingly, running this simple script will open up a window displaying a live video feed from the default webcam. The window can be closed by hitting the escape key. I think this code is pretty self-explanatory, so I won’t dive into it here, but feel free to hit me up if you have any questions!

Example Webcam Capture

#OpenCV #Python #Programming