0
0
Computer-visionHow-ToBeginner ยท 3 min read

How to Read Video in OpenCV for Computer Vision Projects

To read video in OpenCV, use the cv2.VideoCapture class with the video file path or camera index. Then, call read() in a loop to get each frame as an image for processing.
๐Ÿ“

Syntax

The basic syntax to read video in OpenCV involves creating a VideoCapture object and reading frames in a loop.

  • cap = cv2.VideoCapture(source): Opens the video source, where source can be a filename or camera index.
  • ret, frame = cap.read(): Reads the next frame; ret is True if successful, frame is the image.
  • cap.release(): Closes the video file or camera when done.
python
import cv2

cap = cv2.VideoCapture('video.mp4')  # or cap = cv2.VideoCapture(0) for webcam
ret, frame = cap.read()
if ret:
    # process frame
    pass
cap.release()
๐Ÿ’ป

Example

This example opens a video file, reads each frame, shows it in a window, and stops when the video ends or the user presses 'q'.

python
import cv2

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

while True:
    ret, frame = cap.read()
    if not ret:
        break  # End of video
    cv2.imshow('Video Frame', frame)
    if cv2.waitKey(30) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()
Output
A window opens showing video frames until the video ends or 'q' is pressed.
โš ๏ธ

Common Pitfalls

  • Not checking if VideoCapture opened successfully can cause errors.
  • For webcams, the index may vary; 0 is usually the default camera.
  • Not releasing the capture or destroying windows can freeze the program.
  • Using waitKey(0) pauses indefinitely; use a small delay like 30 ms for videos.
python
import cv2

cap = cv2.VideoCapture('nonexistent.mp4')
if not cap.isOpened():
    print('Error: Cannot open video file')
else:
    ret, frame = cap.read()
    if ret:
        cv2.imshow('Frame', frame)
        cv2.waitKey(0)
    cap.release()
    cv2.destroyAllWindows()
Output
Error: Cannot open video file
๐Ÿ“Š

Quick Reference

Remember these key points when reading video in OpenCV:

  • Use cv2.VideoCapture(source) to open video or camera.
  • Use ret, frame = cap.read() to get frames.
  • Check ret to ensure frame was read.
  • Release resources with cap.release() and cv2.destroyAllWindows().
  • Use cv2.waitKey(delay) to control frame display speed.
โœ…

Key Takeaways

Use cv2.VideoCapture with a file path or camera index to open video sources.
Always check if the video source opened successfully with cap.isOpened().
Read frames in a loop using cap.read() and check the return value before processing.
Release the video capture and close windows to free resources after use.
Use cv2.waitKey with a small delay to display video frames smoothly.