Python
Module – 2
[Link] how to read a video file using OpenCV in Python.
1. Use [Link]('filename') to open a video file.
2. Check if the file is opened using [Link]().
3. Read frames using [Link]() in a loop.
4. Display frames using [Link]().
5. Use [Link]() to control playback.
6. Release video using [Link]().
7. Destroy windows using [Link]().
import cv2
cap = [Link]('video.mp4')
while [Link]():
ret, frame = [Link]()
if not ret:
break
[Link]('Video', frame)
if [Link](25) & 0xFF == ord('q'):
break
[Link]()
2. Identify the function used to capture video from a webcam in OpenCV.
1. Use [Link](0) to access the default webcam.
2. Parameter 0 indicates the first camera.
3. Use higher integers for external cameras.
4. Works similarly to reading video files.
5. Returns a VideoCapture object.
6. Can be used with .read() method.
7. Useful for live video applications.
3. List the common video file formats supported by OpenCV.
1. AVI (.avi): Audio Video Interleave format, commonly used with MJPEG or XVID
codecs.
2. MP4 (.mp4): MPEG-4 format using H.264/H.265 codecs, widely used for compressed
video.
3. MOV (.mov): Apple QuickTime format, supports high-quality video, similar to MP4.
4. MKV (.mkv): Matroska format, supports multiple audio/video streams, open and
flexible.
5. FLV (.flv): Flash Video format, used in online streaming, requires FFMPEG support.
6. WMV (.wmv): Windows Media Video format, developed by Microsoft for Windows
systems.
4. Recall the purpose of the cv2.VideoWriter_fourcc() function.
1. It defines the codec used for video compression.
2. Accepts four characters as arguments.
3. Returns a codec code.
4. Common codecs: 'XVID', 'MJPG', 'DIVX', 'MP4V'.
5. Used in [Link]() object.
6. Impacts file size and compatibility.
7. Syntax: fourcc = cv2.VideoWriter_fourcc(*'XVID')
5. What is the role of the [Link](frame) method in video processing?
1. Writes the current video frame to an output file.
2. Used with [Link] object.
3. Should be called inside the frame capture loop.
4. Ensures continuous saving of video.
5. Frame must match the output video size.
6. Maintains frame rate consistency.
7. Example: [Link](frame)
6. Name the parameters used in the [Link]() function to overlay date and time on a
video frame.
1. img: The input image or frame.
2. text: The text string to display.
3. org: Bottom-left corner of the text.
4. fontFace: Font type (e.g., cv2.FONT_HERSHEY_SIMPLEX).
5. fontScale: Font size.
6. color: Text color (e.g., (255,255,255)).
7. thickness: Line thickness.
7. What are the steps to save a video file in OpenCV?
1. Read input video or capture stream.
2. Define frame width and height.
3. Define codec using cv2.VideoWriter_fourcc().
4. Create [Link]() object.
5. Read and write frames using a loop.
6. Use [Link](frame) to save each frame.
import cv2
cap = [Link](0)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = [Link]('[Link]', fourcc, 20.0, (640,480))
while [Link]():
ret, frame = [Link]()
if not ret:
break
[Link](frame)
[Link]('Recording', frame)
if [Link](1) & 0xFF == ord('q'):
break
[Link]()
[Link]()
[Link]()
8. State the purpose of the [Link](), [Link](), and [Link]() functions in video
processing.
1. Used for drawing shapes on video frames.
2. [Link]() draws a line between two points.
3. [Link]() draws a rectangle using top-left and bottom-right corners.
4. [Link]() draws a circle with a center and radius.
5. Useful in object tracking and annotation.
6. Enhances visualization of features.
7. Can be used dynamically in real-time video.
9. Explain the process of adding date and time stamps to a video frame using OpenCV.
1. Import datetime module.
2. Capture current time using [Link]().
3. Convert to string using .strftime().
4. Use [Link]() to overlay on frame.
5. Choose position, font, color, thickness.
6. Use inside the frame capture loop.
7. Display or save the frame with timestamp.
10. Describe how to detect faces in a video stream using Haar cascades in OpenCV.
1. Load pre-trained cascade using [Link].
2. Capture video frames using [Link].
3. Convert frame to grayscale.
4. Apply detectMultiScale() for face detection.
5. Loop over detected faces.
6. Draw rectangles using [Link]().
7. Display or save the output frame.
import cv2
from datetime import datetime
cap = [Link](0)
while True:
ret, frame = [Link]()
timestamp = [Link]().strftime('%Y-%m-%d %H:%M:%S')
[Link](frame, timestamp, (10, 30), cv2.FONT_HERSHEY_SIMPLEX,
1, (255, 255, 255), 2)
[Link]('Timestamped Video', frame)
if [Link](1) & 0xFF == ord('q'):
break
[Link]()
[Link]()
10. Describe how to detect faces in a video stream using Haar cascades in OpenCV.
1. Load pre-trained cascade using [Link].
2. Capture video frames using [Link].
3. Convert frame to grayscale.
4. Apply detectMultiScale() for face detection.
5. Loop over detected faces.
6. Draw rectangles using [Link]().
7. Display or save the output frame.
face_cascade = [Link]('haarcascade_frontalface_default.xml')
cap = [Link](0)
while True:
ret, frame = [Link]()
gray = [Link](frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.1, 4)
for (x, y, w, h) in faces:
[Link](frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
[Link]('Face Detection', frame)
if [Link](1) == ord('q'):
break
[Link]()
[Link]()
11. Discuss the differences between read operations for video files and webcam feeds in
OpenCV.
1. Video files: Use [Link]('filename').
2. Webcam: Use [Link](0) for default camera.
3. Video files are finite; webcams provide continuous stream.
4. Video files may require codec support; webcams use system drivers.
5. Video files have a known frame count; webcams do not.
6. Video file reading can be frame-specific; webcams cannot skip easily.
7. Real-time adjustments are easier with webcams.
12. Summarize how to change video properties such as brightness and contrast
dynamically in a live video stream.
1. Use [Link]() to access webcam.
2. Change properties using [Link](propId, value).
3. Brightness: cv2.CAP_PROP_BRIGHTNESS
4. Contrast: cv2.CAP_PROP_CONTRAST
5. Adjust values in a loop based on conditions or UI.
6. May not work on all devices due to driver limits.
7. Example: [Link](cv2.CAP_PROP_BRIGHTNESS, 0.5)
13. Interpret the frame properties retrieved from a video file using cv2.CAP_PROP_* and
explain their significance.
1. CAP_PROP_FRAME_WIDTH: Width of frames.
2. CAP_PROP_FRAME_HEIGHT: Height of frames.
3. CAP_PROP_FPS: Frames per second.
4. CAP_PROP_FRAME_COUNT: Total number of frames.
5. CAP_PROP_POS_FRAMES: Current frame index.
6. CAP_PROP_POS_MSEC: Current time in milliseconds.
7. Useful for processing, analysis, or debugging.
14. Describe how resizing video frames affects the output video quality and file size.
1. Smaller frames = reduced file size.
2. Lower resolution = reduced image quality.
3. Larger frames = more storage needed.
4. Frame resizing done using [Link]().
5. Affects processing time and memory usage.
6. Impacts compatibility with certain applications.
7. Best to balance quality and size based on need.
resized = [Link](frame, (320, 240))
15. Analyze the use of the detectMultiScale() function in face detection and explain its
parameters.
1. Used with Haar or LBP classifiers.
2. Detects objects at multiple scales.
3. image: Grayscale image input.
4. scaleFactor: Image reduction factor (e.g., 1.1).
5. minNeighbors: Number of neighbor rectangles to retain detection.
6. minSize: Minimum object size.
7. Returns list of rectangles (x, y, w, h).
16. Effect of Changing Video Frame Size on Quality and File Size
1. Reducing frame size decreases resolution.
2. Smaller resolution leads to blurry visuals.
3. File size drops with smaller frames.
4. Increases processing speed.
5. Good for streaming or mobile storage.
6. May lose detail in complex scenes.
7. Use [Link]() to change frame size.
17. Displaying Video Frames Using [Link]() in a Loop
1. Used to show frames in real time.
2. Inside while loop to update each frame.
3. Syntax: [Link]('Window', frame)
4. Needs [Link]() to refresh.
5. Close with [Link]().
6. Good for debugging or live monitoring.
while True:
ret, frame = [Link]()
[Link]('Frame', frame)
if [Link](1) & 0xFF == ord('q'):
break
18. Controlling Video Playback Speed Using [Link]()
1. [Link](ms) controls delay between frames.
2. Lower value = faster playback.
3. Higher value = slower playback.
4. 0 means wait indefinitely.
5. 25ms delay = ~40 FPS.
6. Useful for synchronization.
7. Adjust dynamically for pause/play.
19. Releasing Video Resources Using [Link]() and [Link]()
1. [Link]() stops video capture.
2. Frees system resources.
3. Required for webcams to release device.
4. [Link]() closes all GUI windows.
5. Prevents memory leaks.
6. Use at end of script.
7. Safe video processing practice.
20. Skipping Frames in a Video Using OpenCV
1. Use [Link](cv2.CAP_PROP_POS_FRAMES, frame_number).
2. Jump directly to a specific frame.
3. Helps in sampling or processing specific parts.
4. [Link]() moves one frame forward.
5. Combine loop and conditional skips.
6. Use modulo operator to skip n frames.
7. Useful in surveillance and analytics.
frame_id = 0
while True:
ret, frame = [Link]()
if frame_id % 5 == 0: # process every 5th frame
[Link]('Skipped Frame', frame)
frame_id += 1
21. Converting Video Frames to Grayscale Using OpenCV
1. Convert each frame using [Link]().
2. Syntax: gray = [Link](frame, cv2.COLOR_BGR2GRAY)
3. Reduces data to process.
4. Common for face detection.
5. Grayscale improves speed.
6. Display with [Link]().
7. Save if needed with VideoWriter.
22. Adding a Frame Counter to a Video Using OpenCV and [Link]()
1. Initialize a counter variable.
2. Increment inside video loop.
3. Convert counter to string.
4. Overlay using [Link]().
5. Choose visible position and font.
6. Helps in debugging and analysis.
7. Combine with timestamp if needed.
counter = 0
while True:
ret, frame = [Link]()
counter += 1