VideaHandling
ipynb4 kBPython · 7 cellsSolution of TP 2: Audio and video handling
Video Handling (Using OpenCV - cv2)
This section covers the essential steps for reading, playing, and inspecting video data.
import cv21. Reading and Playing a Video
The fundamental tool for video in OpenCV is the cv2.VideoCapture object.
def play_video(video_path):
# 1. Open the video file
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
print("Error: Could not open video file.")
return
# 2. Loop through frames
while cap.isOpened():
# Read the next frame
ret, frame = cap.read()
# 'ret' (return value) is True if a frame was read successfully
if ret:
# Display the frame
cv2.imshow("Video Playback", frame)
# Wait for 25ms (or less for faster playback).
# The 'q' key stops the loop.
if cv2.waitKey(25) & 0xFF == ord("q"):
break
else:
# End of video stream
break
# 3. Release the capture object and close all windows
cap.release()
cv2.destroyAllWindows()
play_video("path/to/your/video.mp4")2. Inspecting Video Metadata and Data
You can use the .get() method to retrieve key video properties and inspect the frame data itself.
| Property | OpenCV Code | Description |
|---|---|---|
| Frame Width | cap.get(cv2.CAP_PROP_FRAME_WIDTH) | Number of columns (pixels) |
| Frame Height | cap.get(cv2.CAP_PROP_FRAME_HEIGHT) | Number of rows (pixels) |
| Frame Rate (FPS) | cap.get(cv2.CAP_PROP_FPS) | Frames per second |
| Frame Count | cap.get(cv2.CAP_PROP_FRAME_COUNT) | Total number of frames |
Data Inspection:
When you read a frame using ret, frame = cap.read(), the frame variable is a NumPy array.
- Representation: A video frame is just an image! It's a 3D NumPy array of shape (Height, Width, 3) (for BGR color).
- Accessing Data: You can treat it like any image in your image processing labs (e.g., frame[y, x] gives you the BGR color of a specific pixel).