Live Object Detection ពីកាមេរ៉ា និងការវាស់ FPS
ភ្ជាប់ Picamera2 ជាមួយ Detector ដើម្បីរកវត្ថុ Real-time, វាស់ FPS និង Inference Time និងបង្កើត Summary រៀងរាល់វិនាទី។
- ពន្យល់ Edge AI, Quantization (int8) និង Input/Output Tensors របស់ SSD MobileNet
- ដំណើរការ Inference លើរូប ដោយ Preprocessing (BGR→RGB, Resize, dtype) ត្រឹមត្រូវ
- រកវត្ថុពីកាមេរ៉ាផ្ទាល់ កំណត់ Score Threshold និងវាស់ FPS / Inference Time
យើងរុំ Interpreter ក្នុង Class Detector ដែលផ្ទុកម៉ូដែលតែម្ដង ហើយមាន Method detect(frame) ត្រឡប់ List នៃ (label, score, box)។ ការរចនាបែបនេះធ្វើឱ្យយើងយកទៅប្រើឡើងវិញបានក្នុង Flask Dashboard និងគម្រោងទ្វារឆ្លាតវៃ ដោយមិនចម្លងកូដ Preprocess/Postprocess ច្រើនកន្លែង។
FPS ដែលវាស់ពី Frame មួយៗលោតខ្លាំង ដូច្នេះយើងប្រើ Exponential Moving Average៖ FPSavg = 0.9 × FPSavg + 0.1 × FPSnow ដែលធ្វើឱ្យតម្លៃរលូន។ ត្រូវវាស់ Inference Time ដាច់ដោយឡែកពី FPS សរុប ព្រោះ FPS រួមបញ្ចូលទាំងការថត, Preprocess និងការគូរ។ សម្រាប់ SSD MobileNet v1 Quantized លើ CPU Pi 4 ជាធម្មតាទទួលបានត្រឹមប៉ុន្មាន FPS (ប្រហែលមួយខ្ទង់) ហើយ Pi 5 លឿនជាងនោះគួរឱ្យកត់សម្គាល់ — សូមវាស់លើឧបករណ៍របស់អ្នកផ្ទាល់ ព្រោះលទ្ធផលអាស្រ័យលើ OS, កម្ដៅ និង num_threads។
ដើម្បីកុំឱ្យ Output ច្រើនពេក យើងបោះពុម្ព Summary តែម្ដងក្នុងមួយវិនាទី (ឧ. person×2 | FPS 6.1 | infer 120 ms) ហើយរក្សាទុករូបដែលមានប្រអប់រៀងរាល់ 10 វិនាទី។ យើងច្រោះតែប្រភេទវត្ថុដែលចាប់អារម្មណ៍ (WATCH_LABELS) ដើម្បីកាត់បន្ថយ False Positive ពីវត្ថុមិនពាក់ព័ន្ធ។
ការរកឃើញក្នុង Frame តែមួយអាចជា False Positive ដែលកើតឡើងភ្លែតៗ។ ក្នុងប្រព័ន្ធពិត យើងទាមទារឱ្យវត្ថុលេចឡើង N Frame ជាប់គ្នា (ឧ. 3) មុនសម្រេចចិត្ត — បច្ចេកទេស Temporal Filtering នេះនឹងប្រើក្នុងគម្រោងម៉ូឌុលទី ៤។
- រុំ Interpreter ក្នុង Class Detector ដើម្បីប្រើឡើងវិញ
- វាស់ FPS សរុប និង Inference Time ដាច់ដោយឡែក; ប្រើ Moving Average ឱ្យតម្លៃរលូន
- ច្រោះ WATCH_LABELS និងទាមទារ N Frame ជាប់គ្នា ដើម្បីកាត់ False Positive
"""Live object detection from the Pi camera with FPS and inference-time stats."""
import time
from collections import Counter
import cv2
import numpy as np
from picamera2 import Picamera2
try:
from ai_edge_litert.interpreter import Interpreter
except ImportError:
from tflite_runtime.interpreter import Interpreter
MODEL_PATH = "models/detect.tflite"
LABELS_PATH = "models/labelmap.txt"
FRAME_SIZE = (640, 480)
SCORE_THRESHOLD = 0.5
WATCH_LABELS = {"person", "cat", "dog", "car", "bicycle"}
REPORT_EVERY_S = 1.0
SAVE_EVERY_S = 10.0
class Detector:
def __init__(self, model_path, labels_path, threads=4):
with open(labels_path, encoding="utf-8") as f:
labels = [line.strip() for line in f if line.strip()]
self.labels = labels[1:] if labels and labels[0] == "???" else labels
self.interpreter = Interpreter(model_path=model_path, num_threads=threads)
self.interpreter.allocate_tensors()
self.input = self.interpreter.get_input_details()[0]
self.outputs = self.interpreter.get_output_details()
_, self.in_h, self.in_w, _ = [int(v) for v in self.input["shape"]]
self.is_float = self.input["dtype"] == np.float32
self.last_infer_ms = 0.0
def detect(self, frame_bgr, threshold=SCORE_THRESHOLD):
h, w = frame_bgr.shape[:2]
rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB)
tensor = np.expand_dims(cv2.resize(rgb, (self.in_w, self.in_h)), axis=0)
if self.is_float:
tensor = (np.float32(tensor) - 127.5) / 127.5
self.interpreter.set_tensor(self.input["index"], tensor)
start = time.perf_counter()
self.interpreter.invoke()
self.last_infer_ms = (time.perf_counter() - start) * 1000
get = self.interpreter.get_tensor
boxes = get(self.outputs[0]["index"])[0]
classes = get(self.outputs[1]["index"])[0]
scores = get(self.outputs[2]["index"])[0]
count = int(get(self.outputs[3]["index"])[0])
results = []
for i in range(count):
if scores[i] < threshold:
continue
cid = int(classes[i])
label = self.labels[cid] if cid < len(self.labels) else str(cid)
ymin, xmin, ymax, xmax = boxes[i]
box = (max(0, int(xmin * w)), max(0, int(ymin * h)),
min(w - 1, int(xmax * w)), min(h - 1, int(ymax * h)))
results.append((label, float(scores[i]), box))
return results
def draw(frame, detections, fps):
for label, score, (x1, y1, x2, y2) in detections:
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(frame, f"{label} {score:.0%}", (x1, max(15, y1 - 6)),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
cv2.putText(frame, f"FPS {fps:.1f}", (10, 25),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2)
def main():
detector = Detector(MODEL_PATH, LABELS_PATH)
picam2 = Picamera2()
picam2.configure(
picam2.create_video_configuration(main={"size": FRAME_SIZE, "format": "RGB888"})
)
picam2.start()
time.sleep(1)
fps = 0.0
last_time = time.perf_counter()
last_report = last_save = time.monotonic()
try:
while True:
frame = picam2.capture_array()
detections = [d for d in detector.detect(frame) if d[0] in WATCH_LABELS]
now_perf = time.perf_counter()
instant = 1.0 / max(now_perf - last_time, 1e-6)
fps = instant if fps == 0 else 0.9 * fps + 0.1 * instant # smoothed FPS
last_time = now_perf
now = time.monotonic()
if now - last_report >= REPORT_EVERY_S:
counts = Counter(label for label, _, _ in detections)
summary = ", ".join(f"{k} x{v}" for k, v in counts.items()) or "nothing"
print(f"{summary} | FPS {fps:.1f} | infer {detector.last_infer_ms:.0f} ms")
last_report = now
if now - last_save >= SAVE_EVERY_S:
draw(frame, detections, fps)
cv2.imwrite("latest_detection.jpg", frame)
last_save = now
except KeyboardInterrupt:
pass
finally:
picam2.stop()
picam2.close()
if __name__ == "__main__":
main()ការពន្យល់៖ Class Detector ផ្ទុកម៉ូដែល និង Labels តែម្ដង ហើយ detect() ធ្វើ Preprocess → invoke → Postprocess ត្រឡប់ List ដែលងាយប្រើ។ main() គណនា FPS ដោយ Moving Average បោះពុម្ព Summary រៀងរាល់វិនាទី និងរក្សាទុករូបមានប្រអប់រៀងរាល់ 10 វិនាទី។
សំណួរវាស់សមត្ថភាព (Knowledge Check)
ឆ្លើយគ្រប់សំណួរ រួចចុច «ពិនិត្យចម្លើយ»។ បើត្រឹមត្រូវ ≥ ៨០% មេរៀននេះនឹងត្រូវបានកត់ត្រាថាបានបញ្ចប់ស្វ័យប្រវត្តិ។
- Picamera2 Examples (OpenCV & TensorFlow Lite) github.com/raspberrypiFolder examples មានកូដគំរូផ្លូវការសម្រាប់ OpenCV និង Object Detection ជាមួយ Picamera2។