Bird
Raised Fist0
Raspberry Piprogramming~20 mins

Motion detection with camera in Raspberry Pi - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Motion Detection Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this motion detection frame difference code?
Consider this Python snippet using OpenCV on Raspberry Pi to detect motion by frame difference. What will be printed when no motion is detected?
Raspberry Pi
import cv2

frame1 = cv2.imread('frame1.jpg', 0)
frame2 = cv2.imread('frame2.jpg', 0)
diff = cv2.absdiff(frame1, frame2)
non_zero_count = cv2.countNonZero(diff)

if non_zero_count > 1000:
    print('Motion detected')
else:
    print('No motion')
ANo motion
BMotion detected
Ccv2.error: OpenCV(…) error
DTypeError: unsupported operand type(s)
Attempts:
2 left
💡 Hint
Think about what happens when the two frames are identical or very similar.
🧠 Conceptual
intermediate
1:30remaining
Which sensor setup is best for detecting motion with a Raspberry Pi camera?
You want to detect motion using a Raspberry Pi camera module. Which setup will give the most reliable motion detection?
AUse a temperature sensor to detect heat changes
BCompare consecutive frames and check pixel differences
CUse a single frame and check if it is completely black
DCapture one frame per hour and compare with a stored image
Attempts:
2 left
💡 Hint
Motion means change over time in the camera view.
🔧 Debug
advanced
2:30remaining
Why does this Raspberry Pi motion detection code raise an error?
This code snippet is intended to detect motion but raises an error. What is the cause?
Raspberry Pi
import cv2

cap = cv2.VideoCapture(0)
ret, frame1 = cap.read()
ret, frame2 = cap.read()
diff = cv2.absdiff(frame1, frame2)
gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
_, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

for contour in contours:
    if cv2.contourArea(contour) < 1000:
        continue
    cv2.drawContours(frame1, [contour], -1, (0,255,0), 2)

cv2.imshow('Motion', frame1)
cv2.waitKey(0)
cv2.destroyAllWindows()
Acv2.VideoCapture(0) failed to open the camera
Bcv2.drawContours requires grayscale image, not color
Ccv2.findContours returns 3 values, not 2
Dcv2.threshold returns only one value, not two
Attempts:
2 left
💡 Hint
Check the number of values returned by cv2.findContours in your OpenCV version.
📝 Syntax
advanced
2:00remaining
Which option fixes the syntax error in this Raspberry Pi motion detection snippet?
Fix the syntax error in this dictionary comprehension used to count motion pixels: motion_pixels = {x: x*2 if x > 5 for x in range(10)}
Amotion_pixels = {x: (x*2 if x > 5 else 0) for x in range(10)}
Bmotion_pixels = {x: x*2 for x in range(10)}
Cmotion_pixels = {x: x*2 if x > 5 for x in range(10)}
Dmotion_pixels = {x: x*2 for x in range(10) if x > 5}
Attempts:
2 left
💡 Hint
Remember the correct order of if conditions in dictionary comprehensions.
🚀 Application
expert
3:00remaining
How many contours will be detected by this Raspberry Pi motion detection code?
Given this code snippet, how many contours will be detected if the camera captures a static scene with one moving object covering a large area?
Raspberry Pi
import cv2

# Assume frame1 and frame2 are consecutive frames
# with one large moving object

frame1 = cv2.imread('static_scene.jpg')
frame2 = cv2.imread('moving_object.jpg')
diff = cv2.absdiff(frame1, frame2)
gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
_, thresh = cv2.threshold(blur, 25, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

large_contours = [c for c in contours if cv2.contourArea(c) > 5000]
print(len(large_contours))
A1
B0
CMultiple small contours
DRaises an error
Attempts:
2 left
💡 Hint
Think about how a large moving object appears in the thresholded image.

Practice

(1/5)
1. What is the main purpose of motion detection when using a camera on a Raspberry Pi?
easy
A. To increase the camera resolution automatically
B. To find changes between consecutive images
C. To save battery life of the Raspberry Pi
D. To connect the camera to the internet

Solution

  1. Step 1: Understand motion detection basics

    Motion detection works by comparing images to find differences or changes.
  2. Step 2: Identify the main goal of motion detection

    The goal is to detect movement by noticing changes between frames, not to change resolution or save power.
  3. Final Answer:

    To find changes between consecutive images -> Option B
  4. Quick Check:

    Motion detection = find changes [OK]
Hint: Motion detection means spotting changes between pictures [OK]
Common Mistakes:
  • Confusing motion detection with camera settings
  • Thinking motion detection saves power
  • Assuming it connects camera to internet
2. Which of the following Python code snippets correctly imports OpenCV for motion detection on Raspberry Pi?
easy
A. import camera
B. import opencv
C. import cv
D. import cv2

Solution

  1. Step 1: Recall the correct OpenCV import statement

    OpenCV in Python is imported using 'import cv2'.
  2. Step 2: Check other options for correctness

    Options 'opencv', 'cv', and 'camera' are incorrect or outdated module names.
  3. Final Answer:

    import cv2 -> Option D
  4. Quick Check:

    OpenCV import = cv2 [OK]
Hint: OpenCV Python module is always imported as cv2 [OK]
Common Mistakes:
  • Using 'import opencv' instead of 'import cv2'
  • Confusing 'cv' with 'cv2'
  • Trying to import 'camera' module for OpenCV
3. What will be the output of this code snippet when motion is detected?
import cv2
cap = cv2.VideoCapture(0)
ret, frame1 = cap.read()
ret, frame2 = cap.read()
diff = cv2.absdiff(frame1, frame2)
gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 30, 255, cv2.THRESH_BINARY)
print(thresh.sum() > 10000)
medium
A. True if motion detected, False otherwise
B. Always prints True
C. Always prints False
D. Raises a syntax error

Solution

  1. Step 1: Understand the code logic for motion detection

    The code compares two frames, converts difference to grayscale, thresholds it, then sums pixels to detect motion.
  2. Step 2: Interpret the print statement

    If the sum of thresholded pixels is greater than 10000, it prints True (motion detected), else False.
  3. Final Answer:

    True if motion detected, False otherwise -> Option A
  4. Quick Check:

    Threshold sum > 10000 means motion True [OK]
Hint: Sum of thresholded diff > limit means motion detected [OK]
Common Mistakes:
  • Assuming it always prints True or False
  • Confusing thresholding with color conversion
  • Expecting syntax errors from correct code
4. Identify the error in this motion detection code snippet:
import cv2
cap = cv2.VideoCapture(0)
ret, frame1 = cap.read()
ret, frame2 = cap.read()
diff = cv2.absdiff(frame1, frame2)
gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 30, 255, cv2.THRESH_BINARY)
if thresh.sum() > 10000:
    print("Motion detected")
cap.release()
medium
A. Missing loop to continuously read frames
B. Incorrect threshold value used
C. cv2.absdiff should be cv2.subtract
D. cap.release() should be called before reading frames

Solution

  1. Step 1: Check code flow for continuous motion detection

    The code reads frames only once, so it cannot detect motion continuously.
  2. Step 2: Identify missing loop for repeated frame capture

    Motion detection requires a loop to keep reading frames and comparing them over time.
  3. Final Answer:

    Missing loop to continuously read frames -> Option A
  4. Quick Check:

    Continuous detection needs a loop [OK]
Hint: Motion detection needs a loop to compare frames repeatedly [OK]
Common Mistakes:
  • Thinking threshold value is wrong
  • Confusing absdiff with subtract
  • Releasing capture too early
5. You want to trigger an alert only when motion is detected for at least 3 seconds continuously using a Raspberry Pi camera. Which approach is best?
hard
A. Use a timer to trigger alert every 3 seconds regardless of motion
B. Trigger alert immediately on first motion detection
C. Count consecutive frames with motion and trigger alert after threshold
D. Ignore motion and trigger alert manually

Solution

  1. Step 1: Understand the requirement for continuous motion detection

    We need to detect motion lasting at least 3 seconds, not just a single frame.
  2. Step 2: Choose method to track motion duration

    Counting consecutive frames with motion and triggering alert after reaching a threshold time is the best approach.
  3. Final Answer:

    Count consecutive frames with motion and trigger alert after threshold -> Option C
  4. Quick Check:

    Continuous motion needs counting frames [OK]
Hint: Count frames with motion to confirm duration before alert [OK]
Common Mistakes:
  • Triggering alert immediately on any motion
  • Using timer without checking motion
  • Ignoring motion detection logic
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard