How to Work with Camera Feed in Python
A real-time video capture tutorial using OpenCV. Learn to access your webcam, display live video, resize and recolour frames, draw on them, record to a file, and add face detection, all with working code you can run today.
Whether you are building a security camera, a face detection system, or you simply want to learn how to use your webcam with Python, this guide walks you through how to access, display and process a live camera feed in Python using OpenCV. By the end you will be able to capture real-time video, transform it frame by frame, record it to disk, and even detect faces in the stream.
Working with a camera feed is one of the most rewarding things you can do as a beginner, because you get instant visual feedback. Every concept in this tutorial builds towards real projects like motion detectors, attendance systems and live filters.
Tools you need
- Python 3.6 or newer
- OpenCV, imported in code as the
cv2module
If OpenCV is new to you, it is worth exploring our full tutorial on how to use OpenCV in Python first, then returning here to put it to work on live video. Install OpenCV with a single pip command:
pip install opencv-python
Access Your Webcam
OpenCV makes it remarkably easy to start capturing video. The idea is simple: open the camera once, then loop forever, reading and displaying one frame at a time. That continuous loop is what turns a series of still images into live video.
import cv2 # Open the default webcam (index 0) cap = cv2.VideoCapture(0) while True: # Capture frame-by-frame ret, frame = cap.read() # Display the resulting frame cv2.imshow('Webcam Feed', frame) # Exit when 'q' is pressed if cv2.waitKey(1) & 0xFF == ord('q'): break # Release the capture cap.release() cv2.destroyAllWindows()
What each part does
cv2.VideoCapture(0)
Opens the default webcam. The 0 is the camera index.
cap.read()
Grabs the next frame. Returns two values, ret and frame.
ret
A boolean that is True if the frame was read successfully.
frame
The current image from the webcam, stored as a NumPy array.
cv2.imshow()
Displays the frame in a window with the given title.
cv2.waitKey(1)
Waits 1 ms for a key press. This also lets the window refresh.
cap.release() frees the webcam so other programs can use it, and cv2.destroyAllWindows() closes the display windows. Skip them and your camera may stay locked until you restart.
Resize the Frame (Optional)
Processing full-resolution video can be slow, especially once you start adding detection. Resizing each frame to a smaller size speeds everything up and helps the feed fit a fixed user interface. Add this line inside your loop, right after cap.read().
frame = cv2.resize(frame, (640, 480)) # width x height
Convert to Grayscale (or Other Formats)
Many computer vision tasks, including face and motion detection, work on grayscale images because colour is not needed and grayscale is faster to process. OpenCV converts between colour spaces with cvtColor.
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow('Grayscale Feed', gray)
COLOR_BGR2GRAY. If your colours ever look swapped, a BGR to RGB conversion is usually the fix.
Draw on Frames
Because each frame is just an image, you can draw shapes and text directly onto it before displaying. This is how detection boxes, labels and on-screen information get added to a live feed.
# Draw a green rectangle: top-left, bottom-right, colour (BGR), thickness cv2.rectangle(frame, (50, 50), (200, 200), (0, 255, 0), 2) # Draw red text: string, position, font, scale, colour (BGR), thickness cv2.putText(frame, 'Live', (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
(0, 255, 0) is pure green and (0, 0, 255) is pure red. Coordinates are measured in pixels from the top-left corner of the frame.
Save Video from Your Webcam
To record the feed to a file, OpenCV uses a VideoWriter. You tell it the codec, the output filename, the frame rate, and the frame size, then write each frame to it inside the loop.
import cv2 # Define the codec and create a VideoWriter object fourcc = cv2.VideoWriter_fourcc(*'XVID') # or 'MJPG' out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480)) cap = cv2.VideoCapture(0) while cap.isOpened(): ret, frame = cap.read() if ret: out.write(frame) # Save this frame to the file cv2.imshow('Recording...', frame) if cv2.waitKey(1) == ord('q'): break else: break cap.release() out.release() cv2.destroyAllWindows()
VideoWriter, here 640 by 480, must match the size of the frames you write. If you resized the frame earlier, use the same numbers, or the output file will be empty or corrupted. Remember to call out.release() to finish writing the file properly.
Combine with Face Detection
Now for the exciting part. By combining the camera feed with a face detector, you can find and highlight faces in real time. This example uses dlib, a popular library with a fast and accurate frontal face detector.
import dlib detector = dlib.get_frontal_face_detector() while True: ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = detector(gray) for face in faces: x, y, w, h = face.left(), face.top(), face.width(), face.height() cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2) cv2.imshow('Live Detection', frame) if cv2.waitKey(1) == ord('q'): break
The detector runs on the grayscale frame for speed, returns a list of face regions, and then a blue rectangle is drawn around each one on the original colour frame.
Use External or Multiple Cameras
The camera index you pass to VideoCapture selects which camera to use. Index 0 is the default built-in webcam. To use a second, external or USB camera, change the number.
cap = cv2.VideoCapture(1) # or 2, 3, depending on your device
Find out how many cameras are connected
Not sure which index belongs to which camera? Loop through the first few indexes and check which ones respond.
for i in range(5): cap = cv2.VideoCapture(i) if cap.read()[0]: print(f"Camera {i} is available.") cap.release()
Troubleshooting Common Problems
Live video trips up almost every beginner at some point. Here are the most common problems and how to fix them.
| Problem | Solution |
|---|---|
| Black window or crash | Make sure your webcam is not already in use by another app such as a video call |
cv2.error when opening video | Check that the camera index is correct. Try 0, then 1, then 2 |
cap.read() fails | Use cap.isOpened() to confirm the webcam is accessible before reading |
| Video too slow or laggy | Resize the frame, use a faster codec, or install OpenCV built with GPU support |
if not cap.isOpened(): print("Cannot open camera"). Catching the problem early saves you from puzzling over a blank window later.
Summary and Project Ideas
You now have every building block for working with a camera feed in Python. Here is the whole toolkit at a glance.
| Task | Code snippet |
|---|---|
| Open camera | cv2.VideoCapture(0) |
| Read a frame | ret, frame = cap.read() |
| Show a frame | cv2.imshow('Window', frame) |
| Save video | cv2.VideoWriter() |
| Exit the loop | cv2.waitKey(1) == ord('q') |
Project ideas to build next
The best way to lock in these skills is to build something. Here are five projects, each within reach now that you can capture and process live video.
Attendance system
Use face recognition to log who is present automatically.
Motion detector
Compare frames to spot movement and trigger an alert.
Barcode scanner
Read barcodes and QR codes straight from the webcam.
Live drawing app
Track a coloured object and draw on screen as it moves.
Virtual background
Replace your background with a green-screen effect.
