Adv-Py: Unit 2 (Book-back Questions)
Generated and Prepared By Thiruselvan (ThiruXD)
Part B — Short Answer Questions (5 Marks Each)
Q7. Explain the difference between a video container and a codec with suitable examples.
Video Container is the file format that holds the video data, audio data, and metadata together.
Examples: .mp4, .avi, .mkv, .mov
Codec (Coder-Decoder) is the algorithm used to compress and decompress the video data.
Examples: H.264 (avc1), XVID, MJPG, H.265, VP9
Difference:
- Container = Box that stores the content
- Codec = Method used to compress the content inside the box
A single container can support multiple codecs (e.g., an .mp4 file can use H.264 or H.265 codec).
Q8. Write the basic steps required to read and display a video file using OpenCV.
- Import OpenCV library
- Create a
VideoCaptureobject with the video file path - Check whether the video is opened successfully using
cap.isOpened() - Run a loop to read frames one by one using
cap.read() - Check the
retvalue (if False, break the loop) - Display each frame using
cv2.imshow() - Use
cv2.waitKey()to control speed and exit condition - Release the capture object and destroy all windows
Q9. What is frame extraction? Mention three practical applications of extracting frames from a video.
Frame Extraction is the process of reading a video and saving individual frames as separate image files.
Three Practical Applications:
- Creating image datasets for training machine learning models
- Analyzing specific moments (e.g., detecting events at particular timestamps)
- Generating thumbnails or keyframes for video summarization
- Applying image processing techniques on selected frames
Q10. Explain the purpose of cv.waitKey() in video display programs.
cv2.waitKey(delay) waits for a key event for the specified number of milliseconds.
Purpose in video programs:
- Controls the playback speed of the video (e.g.,
waitKey(25)≈ 40 FPS) - Allows the program to refresh the display window
- Used to detect key press (especially ‘q’) to exit the loop gracefully
- Without
waitKey(), the window may not update properly or may freeze
Q11. List any five commonly used VideoCapture properties and explain their use.
cv2.CAP_PROP_FRAME_WIDTH→ Get/Set the width of the framescv2.CAP_PROP_FRAME_HEIGHT→ Get/Set the height of the framescv2.CAP_PROP_FPS→ Get/Set the frames per secondcv2.CAP_PROP_FRAME_COUNT→ Get total number of frames in the videocv2.CAP_PROP_POS_FRAMES→ Get/Set the current frame number (useful for seeking)
Other useful properties: CAP_PROP_POS_MSEC, CAP_PROP_BRIGHTNESS, CAP_PROP_CONTRAST
Q12. Explain how date and time can be added to every frame of a live camera feed.
We use Python’s datetime module to get the current date and time, convert it into a string, and write it on every frame using cv2.putText() inside the video loop.
import datetime
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
cv2.putText(frame, now, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 255), 2)Since this code runs inside the while loop, the time is updated on every frame.
Q13. Differentiate between frame differencing and background subtraction.
| Basis | Frame Differencing | Background Subtraction |
|---|---|---|
| Method | Difference between two consecutive frames | Difference between current frame and a learned background model |
| Background Model | No permanent background model | Maintains a background model |
| Sensitivity | High (detects even small changes) | More robust to gradual changes |
| Complexity | Simple and fast | Slightly more complex |
| Example Functions | cv2.absdiff() | cv2.createBackgroundSubtractorMOG2() |
Q14. What are contours, and how are they used in motion detection?
Contours are the continuous curves or boundaries that join all the points along the boundary of an object having the same colour or intensity.
Use in Motion Detection:
After obtaining the binary foreground mask (white pixels = motion), cv2.findContours() is used to detect the boundaries of the white regions.
Then cv2.boundingRect() is applied on each contour to draw rectangles around moving objects. Small contours (noise) are ignored using area threshold.
Part C — Long Answer / Essay Questions (10 Marks Each)
Q15. Describe the complete OpenCV video processing pipeline. Explain how input video is captured, frames are processed, annotations are added, and output is displayed or written.
Complete Video Processing Pipeline:
-
Input Capture
- File:
cap = cv2.VideoCapture('video.mp4') - Camera:
cap = cv2.VideoCapture(0)
- File:
-
Frame Reading
Loop using
ret, frame = cap.read() -
Preprocessing / Processing
Resize, colour conversion, filtering, motion detection, object tracking etc.
-
Annotation
Draw shapes (
cv2.rectangle,cv2.circle,cv2.line) and text (cv2.putText) including date & time. -
Output
- Display:
cv2.imshow() - Save: Use
cv2.VideoWriterandout.write(frame)
- Display:
-
Release Resources
cap.release(),out.release(),cv2.destroyAllWindows()
Q16. Explain VideoWriter in detail. Discuss the importance of FourCC, FPS and frame size while writing videos. Add a suitable code example.
cv2.VideoWriter is the class used to save processed frames as a video file.
Important Parameters:
- FourCC: Four Character Code that specifies the codec (e.g.,
'XVID','mp4v') - FPS: Frames per second of the output video
- Frame Size: Must match the exact (width, height) of the frames being written
Code Example:
import cv2
cap = cv2.VideoCapture(0)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (width, height))
while True:
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()Q17. Discuss motion detection using OpenCV. Explain background modeling, foreground mask generation, thresholding, contour detection and bounding box drawing.
Steps in Motion Detection:
-
Background Modeling
Maintain a reference background (simple method: previous frame; advanced: MOG2/KNN).
-
Foreground Mask Generation
diff = cv2.absdiff(frame1, frame2)or use background subtractor. -
Preprocessing
Convert to grayscale → Gaussian Blur (noise reduction).
-
Thresholding
Convert difference image into binary image using
cv2.threshold(). -
Morphological Operations
Dilation to fill gaps.
-
Contour Detection
contours, _ = cv2.findContours(...) -
Bounding Box Drawing
For each contour with sufficient area, draw rectangle using
cv2.boundingRect()andcv2.rectangle().
Q18. Explain object tracking in OpenCV. Compare at least four trackers and discuss the challenges faced during tracking.
Object Tracking is the process of locating the same object across consecutive frames after it has been initially selected.
Comparison of Trackers:
| Tracker | Speed | Accuracy | Best Use Case |
|---|---|---|---|
| CSRT | Medium | Very High | Accurate tracking |
| KCF | Fast | Good | Balanced performance |
| MOSSE | Very Fast | Average | Real-time + high FPS |
| MIL | Medium | Good | Handling partial occlusion |
Challenges in Tracking:
- Occlusion (object temporarily hidden)
- Scale change (object moves closer/farther)
- Illumination variation
- Fast motion / motion blur
- Similar looking objects in background
- Object going out of frame
Part D — Analytical / Case-Based Questions
Q19 (Case Study). A college wants to build a camera-based system that records the laboratory entrance, detects movement after working hours, saves the video with date and time, and draws a rectangle around moving objects.
1. What should be used to capture the camera feed?
cv2.VideoCapture(0) or appropriate camera index.
2. How can date and time be displayed on each frame?
Using datetime.datetime.now() and cv2.putText() inside the loop.
3. Which method can be used for motion detection?
Frame Differencing or Background Subtraction (cv2.createBackgroundSubtractorMOG2()).
4. How can the output video be saved?
Using cv2.VideoWriter with proper FourCC, FPS and frame size. Write annotated frames using out.write(frame).
5. What practical problems may affect the system?
- Lighting changes (day/night)
- Shadows detected as motion
- Small moving objects (insects, curtains) causing false alarms
- Camera noise
- Sudden illumination change (lights switched on/off)
- Large file size if recording continuously
Workflow Summary:
Capture → Read frame → Motion detection → Draw rectangle + Date/Time → Write frame to VideoWriter → Display.
Q20 (Compare and Analyse). Construct a detailed comparison between motion detection and object tracking.
| Aspect | Motion Detection | Object Tracking |
|---|---|---|
| Purpose | Detect any moving region | Follow a specific object across frames |
| Input Requirement | No initial object selection needed | Requires initial bounding box (ROI) |
| Output | Binary mask + bounding boxes of all motions | Continuous location of the selected object |
| Algorithms | Frame differencing, MOG2, KNN | CSRT, KCF, MOSSE, MIL, DeepSORT etc. |
| Advantages | Simple, fast, detects any movement | Maintains object identity, works even if object stops |
| Limitations | Cannot identify which object is moving | Fails when object is occluded or moves very fast |
| Suitable Applications | Surveillance alarm, intrusion detection | Player tracking in sports, vehicle tracking, face tracking |
Conclusion:
Motion detection answers “Is something moving?”, while Object Tracking answers “Where did the selected object go?”