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

FPS Optimization

Threading ও multiprocessing।

🎬 গল্প দিয়ে শুরু
আপনার CV app ৭ FPS — অস্বস্তিকর। একই code একটু optimize করলে ৩০ FPS। Real-time vision-এর সাফল্য নির্ভর করে FPS optimization-এর উপর।

প্রথম ধাপ — FPS মাপুন

python
import cv2, time

cap = cv2.VideoCapture(0)
t0, n = time.time(), 0
while True:
    ok, f = cap.read()
    if not ok: break
    n += 1
    if n % 30 == 0:
        fps = n / (time.time() - t0)
        print(f"FPS: {fps:.1f}")
    cv2.imshow("f", f)
    if cv2.waitKey(1) == 27: break

Quick wins

  • Frame resize ছোট করুন (1080p → 640p) → ৩-৪x speed।
  • Color → gray conversion যেখানে সম্ভব।
  • Heavy model প্রতি frame না, প্রতি ৩-৫ frame-এ চালান।
  • imshow / drawing প্রতি 2nd frame-এ; capture+infer প্রতি frame।
  • Buffer size 1 — পুরনো frame queue জমতে দেবেন না।

Threading — Producer/Consumer

cap.read() blocking — থ্রেডে রাখলে main loop free। ১.৫–২x gain সহজে।

python
threaded_cam.py
import cv2, threading, queue

class ThreadedCam:
    def __init__(self, src=0):
        self.cap = cv2.VideoCapture(src)
        self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
        self.q = queue.Queue(maxsize=1)
        self.stop = False
        threading.Thread(target=self._loop, daemon=True).start()

    def _loop(self):
        while not self.stop:
            ok, f = self.cap.read()
            if not ok: break
            if self.q.full():
                try: self.q.get_nowait()
                except queue.Empty: pass
            self.q.put(f)

    def read(self): return self.q.get()
    def close(self):
        self.stop = True; self.cap.release()

Multiprocessing — heavy CPU work

Python-এ GIL-এর কারণে CPU-bound code threading-এ স্পিড পায় না। আলাদা process — multiprocessing.Process বা concurrent.futures.ProcessPoolExecutor

python
from concurrent.futures import ProcessPoolExecutor
pool = ProcessPoolExecutor(max_workers=2)
future = pool.submit(heavy_cv_func, frame)
# মূল thread অন্য কাজ চালিয়ে পরে result নেয়
result = future.result()

GPU / Optimized backend

  • OpenCV CUDA build — cv2.cuda.GpuMat (image processing GPU-তে)।
  • Deep model → ONNX Runtime / TensorRT (Phase 7-এ বিস্তারিত)।
  • PyTorch model — fp16, torch.compile।
  • Apple Silicon — Core ML; Edge — Coral USB।

Profiling — কোথায় slow?

python
import time
def t(name):
    return (name, time.time())

start = time.time()
ts = []
ok, f = cap.read();           ts.append(t("read"))
f2 = cv2.resize(f,(640,360)); ts.append(t("resize"))
g  = cv2.cvtColor(f2,6);      ts.append(t("gray"))
e  = cv2.Canny(g,80,180);     ts.append(t("canny"))

prev = start
for name, now in ts:
    print(f"{name:8s} {(now-prev)*1000:6.2f} ms"); prev = now
প্র্যাকটিস টাস্ক
  1. Threaded vs non-threaded webcam capture-এ FPS তুলনা করুন।
  2. একই pipeline 1080p ও 480p-তে চালিয়ে FPS পার্থক্য measure করুন।
  3. Heavy task (Canny+GaussianBlur বড় kernel) প্রতি 3rd frame-এ চালিয়ে FPS দেখুন।

সারসংক্ষেপ

  • প্রথম পদক্ষেপ = measure; অন্ধভাবে optimize নয়।
  • Resize + skip frame = ৮০% optimization সমাধান।
  • Threading I/O-bound কাজে; multiprocessing CPU-bound কাজে।
  • GPU ব্যবহার করুন যখন model বা batch heavy।