0% found this document useful (0 votes)
0 views10 pages

Python Module 2

This document provides a comprehensive guide on using OpenCV in Python for video processing, including reading video files and webcam feeds, saving videos, and overlaying text. It covers various functions such as cv2.VideoCapture, cv2.VideoWriter, and cv2.putText, along with techniques for face detection, frame manipulation, and dynamic adjustments of video properties. Additionally, it discusses the implications of frame size on quality and file size, and includes code examples for practical implementation.

Uploaded by

juzztrock
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views10 pages

Python Module 2

This document provides a comprehensive guide on using OpenCV in Python for video processing, including reading video files and webcam feeds, saving videos, and overlaying text. It covers various functions such as cv2.VideoCapture, cv2.VideoWriter, and cv2.putText, along with techniques for face detection, frame manipulation, and dynamic adjustments of video properties. Additionally, it discusses the implications of frame size on quality and file size, and includes code examples for practical implementation.

Uploaded by

juzztrock
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Python

Module – 2

1.Define how to read a video file using OpenCV in Python.

1. Use cv2.VideoCapture('filename') to open a video file.

2. Check if the file is opened using cap.isOpened().

3. Read frames using cap.read() in a loop.

4. Display frames using cv2.imshow().

5. Use cv2.waitKey() to control playback.

6. Release video using cap.release().

7. Destroy windows using cv2.destroyAllWindows().

import cv2

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

while cap.isOpened():

ret, frame = cap.read()

if not ret:

break

cv2.imshow('Video', frame)

if cv2.waitKey(25) & 0xFF == ord('q'):

break

cap.release()

2. Identify the function used to capture video from a webcam in OpenCV.

1. Use cv2.VideoCapture(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 cv2.VideoWriter() object.

6. Impacts file size and compatibility.

7. Syntax: fourcc = cv2.VideoWriter_fourcc(*'XVID')

5. What is the role of the out.write(frame) method in video processing?

1. Writes the current video frame to an output file.

2. Used with cv2.VideoWriter 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: out.write(frame)
6. Name the parameters used in the cv2.putText() 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 cv2.VideoWriter() object.

5. Read and write frames using a loop.

6. Use out.write(frame) to save each frame.


import cv2

cap = cv2.VideoCapture(0)

fourcc = cv2.VideoWriter_fourcc(*'XVID')

out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640,480))

while cap.isOpened():

ret, frame = cap.read()

if not ret:

break

out.write(frame)

cv2.imshow('Recording', frame)

if cv2.waitKey(1) & 0xFF == ord('q'):

break
cap.release()

out.release()

cv2.destroyAllWindows()

8. State the purpose of the cv2.line(), cv2.rectangle(), and cv2.circle() functions in video
processing.

1. Used for drawing shapes on video frames.

2. cv2.line() draws a line between two points.

3. cv2.rectangle() draws a rectangle using top-left and bottom-right corners.

4. cv2.circle() 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 datetime.now().

3. Convert to string using .strftime().

4. Use cv2.putText() 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 cv2.CascadeClassifier.

2. Capture video frames using cv2.VideoCapture.

3. Convert frame to grayscale.

4. Apply detectMultiScale() for face detection.

5. Loop over detected faces.

6. Draw rectangles using cv2.rectangle().

7. Display or save the output frame.

import cv2

from datetime import datetime

cap = cv2.VideoCapture(0)

while True:

ret, frame = cap.read()

timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

cv2.putText(frame, timestamp, (10, 30), cv2.FONT_HERSHEY_SIMPLEX,

1, (255, 255, 255), 2)

cv2.imshow('Timestamped Video', frame)

if cv2.waitKey(1) & 0xFF == ord('q'):

break

cap.release()

cv2.destroyAllWindows()

10. Describe how to detect faces in a video stream using Haar cascades in OpenCV.

1. Load pre-trained cascade using cv2.CascadeClassifier.

2. Capture video frames using cv2.VideoCapture.

3. Convert frame to grayscale.

4. Apply detectMultiScale() for face detection.


5. Loop over detected faces.

6. Draw rectangles using cv2.rectangle().

7. Display or save the output frame.

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

cap = cv2.VideoCapture(0)

while True:

ret, frame = cap.read()

gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(gray, 1.1, 4)

for (x, y, w, h) in faces:

cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)

cv2.imshow('Face Detection', frame)

if cv2.waitKey(1) == ord('q'):

break

cap.release()

cv2.destroyAllWindows()

11. Discuss the differences between read operations for video files and webcam feeds in
OpenCV.

1. Video files: Use cv2.VideoCapture('filename').

2. Webcam: Use cv2.VideoCapture(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 cv2.VideoCapture() to access webcam.

2. Change properties using cap.set(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: cap.set(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 cv2.resize().

5. Affects processing time and memory usage.

6. Impacts compatibility with certain applications.

7. Best to balance quality and size based on need.

resized = cv2.resize(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 cv2.resize() to change frame size.

17. Displaying Video Frames Using cv2.imshow() in a Loop

1. Used to show frames in real time.

2. Inside while loop to update each frame.

3. Syntax: cv2.imshow('Window', frame)

4. Needs cv2.waitKey() to refresh.

5. Close with cv2.destroyAllWindows().

6. Good for debugging or live monitoring.


while True:

ret, frame = cap.read()

cv2.imshow('Frame', frame)

if cv2.waitKey(1) & 0xFF == ord('q'):

break
18. Controlling Video Playback Speed Using cv2.waitKey()

1. cv2.waitKey(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 cap.release() and cv2.destroyAllWindows()

1. cap.release() stops video capture.

2. Frees system resources.

3. Required for webcams to release device.

4. cv2.destroyAllWindows() 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 cap.set(cv2.CAP_PROP_POS_FRAMES, frame_number).

2. Jump directly to a specific frame.

3. Helps in sampling or processing specific parts.

4. cap.read() 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 = cap.read()

if frame_id % 5 == 0: # process every 5th frame

cv2.imshow('Skipped Frame', frame)

frame_id += 1

21. Converting Video Frames to Grayscale Using OpenCV

1. Convert each frame using cv2.cvtColor().

2. Syntax: gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

3. Reduces data to process.

4. Common for face detection.

5. Grayscale improves speed.

6. Display with cv2.imshow().

7. Save if needed with VideoWriter.

22. Adding a Frame Counter to a Video Using OpenCV and cv2.putText()

1. Initialize a counter variable.

2. Increment inside video loop.

3. Convert counter to string.

4. Overlay using cv2.putText().

5. Choose visible position and font.

6. Helps in debugging and analysis.

7. Combine with timestamp if needed.

counter = 0

while True:

ret, frame = cap.read()

counter += 1

You might also like