15
OpenCV is a powerful library for computer vision, and one of its core functionalities is capturing video from cameras or video files. This tutorial will guide you through the process of capturing, processing, and saving video using OpenCV.
What You’ll Learn
1. Introduction to Video Capture
The class cv2.VideoCapture is used to capture video. It can:
- Access live video from a webcam.
- Read video files from disk.
2. Capturing Video from a Webcam
Example: Capture Video from Webcam
import cv2 # Initialize video capture (0 for the default camera) cap = cv2.VideoCapture(0) if not cap.isOpened(): print("Error: Could not open webcam.") exit() while True: # Capture frame-by-frame ret, frame = cap.read() # Check if the frame was successfully captured if not ret: print("Error: Failed to capture frame.") break # Display the frame cv2.imshow("Webcam Feed", frame) # Break the loop on 'q' key press if cv2.waitKey(1) & 0xFF == ord('q'): break # Release the capture and close windows cap.release() cv2.destroyAllWindows()
3. Capturing Video from a File
Example: Read Video from File
import cv2 # Open a video file cap = cv2.VideoCapture("video.mp4") if not cap.isOpened(): print("Error: Could not open video file.") exit() while True: # Capture frame-by-frame ret, frame = cap.read() # Break the loop if no frames are left if not ret: print("End of video.") break # Display the frame cv2.imshow("Video Playback", frame) # Break the loop on 'q' key press if cv2.waitKey(30) & 0xFF == ord('q'): break # Release the capture and close windows cap.release() cv2.destroyAllWindows()
4. Displaying Video Frames
Frames captured using cv2.VideoCapture can be displayed using cv2.imshow.
Example: Resize and Display Video Frames
import cv2 cap = cv2.VideoCapture(0) while True: ret, frame = cap.read() if not ret: break # Resize the frame to half its original size resized_frame = cv2.resize(frame, None, fx=0.5, fy=0.5) # Display the resized frame cv2.imshow("Resized Webcam Feed", resized_frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
5. Saving Captured Video
Use cv2.VideoWriter to save video frames to a file.
Example: Save Webcam Feed to File
import cv2 # Initialize webcam cap = cv2.VideoCapture(0) # Define the codec and create VideoWriter object fourcc = cv2.VideoWriter_fourcc(*'XVID') # XVID codec out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480)) if not cap.isOpened(): print("Error: Could not open webcam.") exit() while True: ret, frame = cap.read() if not ret: break # Write the frame to the file out.write(frame) # Display the frame cv2.imshow("Recording Webcam", frame) if cv2.waitKey(1) & 0xFF == ord('q'): break # Release resources cap.release() out.release() cv2.destroyAllWindows()
6. Processing Video Frames
Example: Convert Frames to Grayscale
import cv2 cap = cv2.VideoCapture(0) while True: ret, frame = cap.read() if not ret: break # Convert the frame to grayscale gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Display the grayscale frame cv2.imshow("Grayscale Webcam Feed", gray_frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
Example: Apply Edge Detection
import cv2 cap = cv2.VideoCapture(0) while True: ret, frame = cap.read() if not ret: break # Apply Canny edge detection edges = cv2.Canny(frame, 100, 200) # Display the edges cv2.imshow("Edge Detection", edges) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
7. Practical Examples
7.1 Capture and Save Video with Timestamp
import cv2 from datetime import datetime cap = cv2.VideoCapture(0) fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter('output_with_timestamp.avi', fourcc, 20.0, (640, 480)) while True: ret, frame = cap.read() if not ret: break # Add a timestamp to the frame timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") cv2.putText(frame, timestamp, (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) # Write and display the frame out.write(frame) cv2.imshow("Video with Timestamp", frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() out.release() cv2.destroyAllWindows()
7.2 Extract Frames from Video
import cv2 import os # Open a video file cap = cv2.VideoCapture("video.mp4") output_dir = "extracted_frames" os.makedirs(output_dir, exist_ok=True) frame_count = 0 while True: ret, frame = cap.read() if not ret: break # Save every 10th frame if frame_count % 10 == 0: frame_path = os.path.join(output_dir, f"frame_{frame_count}.jpg") cv2.imwrite(frame_path, frame) frame_count += 1 cap.release() print("Frames extracted and saved!")
8. Summary
- Capturing Video:
- Use cv2.VideoCapture(0) for webcam or specify a video file path.
- Displaying Video:
- Use cv2.imshow() to display video frames in a window.
- Saving Video:
- Use cv2.VideoWriter to save video to a file.
- Processing Frames:
- Apply transformations like resizing, grayscale, or edge detection to frames.
Key Functions
- cv2.VideoCapture(): Captures video from a source.
- cv2.imshow(): Displays video frames.
- cv2.VideoWriter(): Saves video to a file.
- cv2.cvtColor(): Converts color spaces (e.g., to grayscale).
By combining these techniques, you can build powerful video processing applications using OpenCV!