BTCE | 5th Sem
Adv-Python SubjectExtra Questions

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.

  1. Import OpenCV library
  2. Create a VideoCapture object with the video file path
  3. Check whether the video is opened successfully using cap.isOpened()
  4. Run a loop to read frames one by one using cap.read()
  5. Check the ret value (if False, break the loop)
  6. Display each frame using cv2.imshow()
  7. Use cv2.waitKey() to control speed and exit condition
  8. 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:

  1. Creating image datasets for training machine learning models
  2. Analyzing specific moments (e.g., detecting events at particular timestamps)
  3. Generating thumbnails or keyframes for video summarization
  4. 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.

  1. cv2.CAP_PROP_FRAME_WIDTH → Get/Set the width of the frames
  2. cv2.CAP_PROP_FRAME_HEIGHT → Get/Set the height of the frames
  3. cv2.CAP_PROP_FPS → Get/Set the frames per second
  4. cv2.CAP_PROP_FRAME_COUNT → Get total number of frames in the video
  5. cv2.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.

BasisFrame DifferencingBackground Subtraction
MethodDifference between two consecutive framesDifference between current frame and a learned background model
Background ModelNo permanent background modelMaintains a background model
SensitivityHigh (detects even small changes)More robust to gradual changes
ComplexitySimple and fastSlightly more complex
Example Functionscv2.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:

  1. Input Capture

    • File: cap = cv2.VideoCapture('video.mp4')
    • Camera: cap = cv2.VideoCapture(0)
  2. Frame Reading

    Loop using ret, frame = cap.read()

  3. Preprocessing / Processing

    Resize, colour conversion, filtering, motion detection, object tracking etc.

  4. Annotation

    Draw shapes (cv2.rectangle, cv2.circle, cv2.line) and text (cv2.putText) including date & time.

  5. Output

    • Display: cv2.imshow()
    • Save: Use cv2.VideoWriter and out.write(frame)
  6. 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:

  1. Background Modeling

    Maintain a reference background (simple method: previous frame; advanced: MOG2/KNN).

  2. Foreground Mask Generation

    diff = cv2.absdiff(frame1, frame2) or use background subtractor.

  3. Preprocessing

    Convert to grayscale → Gaussian Blur (noise reduction).

  4. Thresholding

    Convert difference image into binary image using cv2.threshold().

  5. Morphological Operations

    Dilation to fill gaps.

  6. Contour Detection

    contours, _ = cv2.findContours(...)

  7. Bounding Box Drawing

    For each contour with sufficient area, draw rectangle using cv2.boundingRect() and cv2.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:

TrackerSpeedAccuracyBest Use Case
CSRTMediumVery HighAccurate tracking
KCFFastGoodBalanced performance
MOSSEVery FastAverageReal-time + high FPS
MILMediumGoodHandling 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.

AspectMotion DetectionObject Tracking
PurposeDetect any moving regionFollow a specific object across frames
Input RequirementNo initial object selection neededRequires initial bounding box (ROI)
OutputBinary mask + bounding boxes of all motionsContinuous location of the selected object
AlgorithmsFrame differencing, MOG2, KNNCSRT, KCF, MOSSE, MIL, DeepSORT etc.
AdvantagesSimple, fast, detects any movementMaintains object identity, works even if object stops
LimitationsCannot identify which object is movingFails when object is occluded or moves very fast
Suitable ApplicationsSurveillance alarm, intrusion detectionPlayer tracking in sports, vehicle tracking, face tracking

Conclusion:

Motion detection answers “Is something moving?”, while Object Tracking answers “Where did the selected object go?”


On this page