অধ্যায়Phase 4 · ভিডিও ও রিয়েল-টাইম সিস্টেম
4.5 10 মিনিট পড়া

Real-Time Vision Systems

Latency budget ও design।

🎬 গল্প দিয়ে শুরু
ATM-এর face match হতে হবে < ১ সেকেন্ডে। Drone-এর obstacle avoid হতে হবে ৫০ ms-এ। Real-time vision system মানে শুধু “কাজ করে” না — “সময়মতো কাজ করে”। এই অধ্যায়ে production-grade architecture।

Latency Budget

প্রতিটি real-time system-এর একটি “সময়ের বাজেট” থাকে। যেমন ৩০ FPS = ৩৩ ms প্রতি frame। সেই ৩৩ ms-এ ভাগ করতে হয়:

text
Capture          ~3 ms
Pre-process      ~2 ms
Inference        ~15 ms   ← সবচেয়ে costly
Post-process     ~3 ms
Tracking/logic   ~5 ms
Display/encode   ~5 ms
────────────────────────
Total            ~33 ms
মূল শিক্ষা
“Average FPS” নয়, worst-case latency নিয়ে চিন্তা করুন। ১ frame ৩০০ ms নিলেই user-এর কাছে hang।

Architecture Patterns

  • Single-thread loop — সহজ, ছোট app। FPS = সব stage যোগ।
  • Producer-Consumer (queue) — capture আলাদা thread, processing main। 1.5-2× gain।
  • Multi-stage pipeline — প্রতিটি stage আলাদা thread; queue দিয়ে যুক্ত।
  • Microservice — capture, inference, storage আলাদা service (gRPC/Kafka)।
text
         queue           queue           queue
[Capture] ────► [Pre] ────► [Infer] ────► [Post/UI]
   T1            T2          T3 (GPU)        T4

Frame Drop Strategy

Slow inference হলে frame কেমন handle করবেন?

  • Drop old — latest frame-এর উপর কাজ; backlog ফেলে দিন (live UI-র জন্য best)।
  • Buffer + skip — fixed-size queue, full হলে oldest discard।
  • Adaptive resolution — slow হলে ছোট resolution-এ switch।
  • Result caching — পরের frame-এ আগের bbox reuse + tracker।

Health Monitoring

python
import time, collections

class Monitor:
    def __init__(self, window=30):
        self.times = collections.deque(maxlen=window)
    def tick(self):
        self.times.append(time.time())
    def fps(self):
        if len(self.times) < 2: return 0
        return (len(self.times)-1) / (self.times[-1]-self.times[0])

Production-এ এই FPS/latency metric → Prometheus/Grafana-তে পাঠালে issue দ্রুত ধরা পড়ে।

Real-time checklist

  • Capture buffer 1, drop-oldest queue।
  • Inference batch 1, fp16/int8 যেখানে সম্ভব।
  • Logging async; disk write আলাদা thread।
  • Graceful shutdown — Ctrl-C-এ writer release।
  • Fallback — model fail → simple CV fallback (motion detect)।
  • Reconnect — RTSP drop হলে auto-retry exponential backoff।

End-to-end skeleton

python
rt_system.py
import cv2, threading, queue, time

frames = queue.Queue(maxsize=1)
results = queue.Queue(maxsize=1)
stop = threading.Event()

def capture(src):
    cap = cv2.VideoCapture(src)
    while not stop.is_set():
        ok, f = cap.read()
        if not ok: break
        if frames.full():
            try: frames.get_nowait()
            except queue.Empty: pass
        frames.put(f)
    cap.release()

def infer():
    while not stop.is_set():
        try: f = frames.get(timeout=1)
        except queue.Empty: continue
        # heavy model এখানে
        out = cv2.Canny(cv2.cvtColor(f, cv2.COLOR_BGR2GRAY), 80, 180)
        if results.full():
            try: results.get_nowait()
            except queue.Empty: pass
        results.put((f, out))

threading.Thread(target=capture, args=(0,), daemon=True).start()
threading.Thread(target=infer, daemon=True).start()

try:
    while True:
        f, out = results.get()
        vis = cv2.addWeighted(f, 0.7,
              cv2.cvtColor(out, cv2.COLOR_GRAY2BGR), 0.3, 0)
        cv2.imshow("rt", vis)
        if cv2.waitKey(1) == 27: break
finally:
    stop.set(); cv2.destroyAllWindows()

Phase 4 শেষ — কী শিখলেন?

  • Video processing = per-frame pipeline।
  • Webcam, IP cam, RTSP — সব source handle।
  • FPS optimization — resize, skip, thread, GPU।
  • Object tracking — KCF/CSRT, multi-tracker, detect+track hybrid।
  • Real-time architecture — latency budget, frame drop, monitoring।
পরবর্তী — Phase 5: Deep Learning for Vision
Classical CV ও real-time pipeline তৈরি। এখন আমরা যোগ করব AI brain — CNN, transfer learning, YOLO, segmentation, OCR, pose। আধুনিক CV-এর হৃদয়।
প্র্যাকটিস টাস্ক
  1. Producer-consumer queue দিয়ে webcam + edge detection pipeline বানান।
  2. Drop-oldest queue ও blocking queue দুটোর FPS ও latency তুলনা করুন।
  3. RTSP URL drop হলে auto-reconnect + log লেখার robust loop তৈরি করুন।