অধ্যায়Phase 3 · ক্লাসিক্যাল কম্পিউটার ভিশন
3.5 20 মিনিট পড়া

Motion Detection

Frame differencing।

🎬 গল্প দিয়ে শুরু
CCTV-এ যদি কেউ ঢোকে, alert পাঠাতে হবে। প্রতিটি frame model-এ পাঠানো ব্যয়বহুল। সহজ সমাধান — Motion Detection। আগের frame-এর সাথে এখনকার frame-এর তফাত।

Frame Differencing — সবচেয়ে সরল

python
motion.py
import cv2

cap = cv2.VideoCapture(0)
ret, prev = cap.read()
prev = cv2.cvtColor(prev, cv2.COLOR_BGR2GRAY)
prev = cv2.GaussianBlur(prev, (21,21), 0)

while True:
    ret, frame = cap.read()
    if not ret: break
    g = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    g = cv2.GaussianBlur(g, (21,21), 0)

    delta = cv2.absdiff(prev, g)
    _, th = cv2.threshold(delta, 25, 255, cv2.THRESH_BINARY)
    th = cv2.dilate(th, None, iterations=2)

    cnts, _ = cv2.findContours(th, cv2.RETR_EXTERNAL,
                               cv2.CHAIN_APPROX_SIMPLE)
    for c in cnts:
        if cv2.contourArea(c) < 800: continue
        x,y,w,h = cv2.boundingRect(c)
        cv2.rectangle(frame, (x,y), (x+w,y+h), (0,255,0), 2)
        cv2.putText(frame, "MOTION", (x,y-8),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0,0,255), 2)

    cv2.imshow("Motion", frame)
    if cv2.waitKey(1) == 27: break
    prev = g

cap.release(); cv2.destroyAllWindows()

Three-frame differencing

দুটো consecutive diff-এর AND নিলে false motion আরও কমে — slow lighting change ignore হয়।

python
d1 = cv2.absdiff(f1, f2)
d2 = cv2.absdiff(f2, f3)
motion = cv2.bitwise_and(d1, d2)

Practical pitfalls

  • আলো হঠাৎ বদলালে পুরো frame motion দেখাবে — adaptive background দরকার।
  • Wind-এ গাছের পাতা — শুধু large contour ধরুন (area filter)।
  • Camera shake — stabilization বা ROI restrict করুন।
  • Night vision — IR illumination + sensitivity tune।

Mini project — Auto record on motion

python
import cv2, time

cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
writer = None
last_motion = 0

# ... motion detection loop ...
if motion_detected:
    last_motion = time.time()
    if writer is None:
        writer = cv2.VideoWriter(f"clip_{int(time.time())}.mp4",
                                 fourcc, 20, (640,480))

if writer is not None:
    writer.write(frame)
    if time.time() - last_motion > 5:    # 5s idle → stop
        writer.release(); writer = None
প্র্যাকটিস টাস্ক
  1. Webcam-এ frame-diff motion detector বানান, contour size threshold ৫০০।
  2. Three-frame diff vs simple diff তুলনা করে false positive count করুন।
  3. Motion হলে console-এ timestamp log করুন (mini intrusion logger)।

সারসংক্ষেপ

  • Motion = frame-to-frame intensity পরিবর্তন।
  • absdiff + threshold + dilate + contour = সরল pipeline।
  • Lighting/wind/camera shake — সব real-world challenge।
  • Heavy model run-এর আগে motion ROI দিয়ে compute কমান।