0
0
Computer Visionml~5 mins

Reading video with OpenCV in Computer Vision

Choose your learning style9 modes available
Introduction
We read videos to process and analyze moving images frame by frame, like watching a movie but with a computer.
To analyze security camera footage for unusual activity.
To detect and track objects in a sports game video.
To extract frames from a video for image processing tasks.
To create a real-time video filter or effect.
To convert video into a sequence of images for machine learning.
Syntax
Computer Vision
import cv2

cap = cv2.VideoCapture('video.mp4')

while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break
    # process the frame here

cap.release()
cv2.VideoCapture opens the video file or camera stream.
cap.read() returns two values: ret (True if frame read) and frame (the image).
Examples
Open the default webcam instead of a video file.
Computer Vision
cap = cv2.VideoCapture(0)
Read one frame and show it in a window if successful.
Computer Vision
ret, frame = cap.read()
if ret:
    cv2.imshow('Frame', frame)
Read frames in a loop and convert each to grayscale.
Computer Vision
while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
Sample Model
This program opens your webcam, shows the video live, counts frames, and stops when you press 'q'.
Computer Vision
import cv2

cap = cv2.VideoCapture(0)  # Open webcam

frame_count = 0
while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break
    frame_count += 1
    cv2.imshow('Webcam Frame', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()
print(f'Total frames read: {frame_count}')
OutputSuccess
Important Notes
Always call cap.release() to free the video resource.
Use cv2.waitKey() to allow OpenCV to process window events.
Press 'q' to quit the video window in the sample program.
Summary
Use cv2.VideoCapture to open video files or cameras.
Read frames one by one with cap.read().
Release resources and close windows after processing.