Python · Computer Vision

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.

Beginner friendly OpenCV · cv2 ~18 min read

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 cv2 module

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:

terminal
pip install opencv-python
Step 1

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.

Always release the camera
The final two lines matter. 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.
Why the frame is a NumPy array
Each frame OpenCV hands you is really a grid of pixel values held in a NumPy array. That is why image processing and array skills go hand in hand. If arrays are new to you, our guide to NumPy in Python explains the foundation.

Step 2

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
Speed matters in real time
A smaller frame means fewer pixels to process, which raises your frame rate. If your feed feels laggy, resizing is the first and easiest fix to try.

Step 3

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)
OpenCV uses BGR, not RGB
This catches almost everyone out. OpenCV loads colour images in Blue-Green-Red order, not the usual Red-Green-Blue. That is why the conversion flag is COLOR_BGR2GRAY. If your colours ever look swapped, a BGR to RGB conversion is usually the fix.

Step 4

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)
Remember the colour order
Colours are given as (Blue, Green, Red). So (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.

Step 5

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()
Match the frame size exactly
The size you give 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.

Step 6

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.

Go deeper on detection
This is only the beginning of what is possible. To learn the detector properly, see our guide on using dlib in Python, then move on to face recognition in Python and even building a complete face recognition system.

Step 7

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()
Example outputCamera 0 is available. Camera 1 is available.

Step 8

Troubleshooting Common Problems

Live video trips up almost every beginner at some point. Here are the most common problems and how to fix them.

ProblemSolution
Black window or crashMake sure your webcam is not already in use by another app such as a video call
cv2.error when opening videoCheck that the camera index is correct. Try 0, then 1, then 2
cap.read() failsUse cap.isOpened() to confirm the webcam is accessible before reading
Video too slow or laggyResize the frame, use a faster codec, or install OpenCV built with GPU support
A reliable startup check
Right after creating your capture, add if not cap.isOpened(): print("Cannot open camera"). Catching the problem early saves you from puzzling over a blank window later.

Recap

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.

TaskCode snippet
Open cameracv2.VideoCapture(0)
Read a frameret, frame = cap.read()
Show a framecv2.imshow('Window', frame)
Save videocv2.VideoWriter()
Exit the loopcv2.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.

Where to go next
Camera work sits inside the wider world of computer vision. To keep progressing in a sensible order, follow our structured Python roadmap, and strengthen your core skills with the complete Python notes.
Ready to build a full vision project?
You can now capture and process live video. The next step is putting it to work. Follow the Python roadmap to move from webcam basics to complete computer vision applications.
View the Python roadmap
Scroll to Top