ដំណើរការ Object Detection លើរូបភាព: Preprocess, Invoke, Postprocess
សរសេរកម្មវិធីដែលផ្ទុកម៉ូដែល .tflite រៀបចំ Input Tensor ត្រឹមត្រូវ អាន Output ៤ Tensor និងគូរប្រអប់លើវត្ថុដែលរកឃើញ។
- ពន្យល់ Edge AI, Quantization (int8) និង Input/Output Tensors របស់ SSD MobileNet
- ដំណើរការ Inference លើរូប ដោយ Preprocessing (BGR→RGB, Resize, dtype) ត្រឹមត្រូវ
- រកវត្ថុពីកាមេរ៉ាផ្ទាល់ កំណត់ Score Threshold និងវាស់ FPS / Inference Time
លំដាប់ការងាររបស់ Interpreter៖ Interpreter(model_path=..., num_threads=4) → allocate_tensors() → អាន get_input_details() / get_output_details() → set_tensor() → invoke() → get_tensor()។ num_threads=4 អនុញ្ញាតឱ្យប្រើ CPU Cores ទាំង ៤ របស់ Pi 4/5។ កុំហៅ allocate_tensors() ក្នុង Loop — ហៅតែម្ដងពេលចាប់ផ្ដើម។
Preprocessing ត្រូវតែដូចពេល Training៖ ម៉ូដែលបង្វឹកលើរូប RGB ដូច្នេះត្រូវបម្លែង cv2.COLOR_BGR2RGB ពី OpenCV, Resize ទៅ 300×300 (អានពី Input Shape [1, 300, 300, 3] កុំសរសេរលេខរឹង) និងបន្ថែម Batch Dimension ដោយ np.expand_dims(img, axis=0)។ ម៉ូដែល Quantized ទទួល uint8 (0–255) ដោយផ្ទាល់ ចំណែកម៉ូដែល float32 ត្រូវ Normalize (x - 127.5)/127.5 ទៅចន្លោះ −1…1។ ការភ្លេចបម្លែង BGR→RGB មិនធ្វើឱ្យ Error ទេ តែធ្វើឱ្យភាពត្រឹមត្រូវធ្លាក់ដោយស្ងាត់ៗ — Bug ដែលពិបាករកបំផុត!
Output របស់ SSD MobileNet v1 (TFLite_Detection_PostProcess)៖ Tensor 0 = boxes [1, N, 4] (ymin, xmin, ymax, xmax ជាតម្លៃ 0–1 → គុណនឹង Height/Width ដើម្បីបាន Pixel), Tensor 1 = class IDs, Tensor 2 = scores (0–1), Tensor 3 = ចំនួន Detection។ ម៉ូដែលផ្សេង (ឧ. Export ពី TF2) អាចមានលំដាប់ Output ខុសគ្នា — ត្រូវពិនិត្យ get_output_details() ជានិច្ចពេលប្ដូរម៉ូដែល។ ឯកសារ labelmap.txt របស់ម៉ូដែលគំរូនេះមានបន្ទាត់ទីមួយ ??? ជា Placeholder ដែលត្រូវលុបចេញ ដើម្បីឱ្យ Class 0 = person។
Score Threshold (ឧ. 0.5) កំណត់ការដោះដូររវាង False Positive និង False Negative៖ Threshold ទាប (0.3) រកបានច្រើន តែខុសច្រើន; Threshold ខ្ពស់ (0.7) ច្បាស់ តែអាចរំលងវត្ថុតូច ឬឆ្ងាយ។ SSD MobileNet 300×300 មិនពូកែរកវត្ថុតូចៗនៅឆ្ងាយទេ — ដាក់កាមេរ៉ាឱ្យវត្ថុគោលដៅកាន់កាប់ផ្ទៃរូបបានច្រើនល្មម។
- allocate_tensors() ម្ដង; set_tensor → invoke → get_tensor រាល់ Frame
- Preprocess៖ BGR→RGB, Resize តាម Input Shape, expand_dims, uint8 ឬ Normalize សម្រាប់ float
- Boxes ជាតម្លៃ 0–1 លំដាប់ (ymin, xmin, ymax, xmax) — គុណនឹងទំហំរូប
- Score Threshold ដោះដូររវាង False Positive និង False Negative
"""Run a quantized SSD MobileNet (COCO) .tflite model on one image.
Usage: python detect_image.py test.jpg
"""
import sys
import time
import cv2
import numpy as np
try:
from ai_edge_litert.interpreter import Interpreter # LiteRT (new name)
except ImportError:
from tflite_runtime.interpreter import Interpreter # legacy package
MODEL_PATH = "models/detect.tflite"
LABELS_PATH = "models/labelmap.txt"
SCORE_THRESHOLD = 0.5
def load_labels(path):
with open(path, encoding="utf-8") as f:
labels = [line.strip() for line in f if line.strip()]
if labels and labels[0] == "???": # starter model: first line is a placeholder
labels = labels[1:]
return labels
def main():
image_path = sys.argv[1] if len(sys.argv) > 1 else "test.jpg"
labels = load_labels(LABELS_PATH)
interpreter = Interpreter(model_path=MODEL_PATH, num_threads=4)
interpreter.allocate_tensors()
input_info = interpreter.get_input_details()[0]
output_info = interpreter.get_output_details()
_, in_h, in_w, _ = [int(v) for v in input_info["shape"]]
is_float = input_info["dtype"] == np.float32
print(f"Model input: {in_w}x{in_h}, dtype={input_info['dtype'].__name__}")
image_bgr = cv2.imread(image_path)
if image_bgr is None:
raise SystemExit(f"Cannot read image: {image_path}")
img_h, img_w = image_bgr.shape[:2]
# Preprocess exactly like training: RGB, model size, batch dimension
rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
tensor = np.expand_dims(cv2.resize(rgb, (in_w, in_h)), axis=0)
if is_float:
tensor = (np.float32(tensor) - 127.5) / 127.5
interpreter.set_tensor(input_info["index"], tensor)
start = time.perf_counter()
interpreter.invoke()
infer_ms = (time.perf_counter() - start) * 1000
# SSD MobileNet v1 post-processed outputs:
# 0 boxes [1,N,4] (ymin, xmin, ymax, xmax; 0-1), 1 classes [1,N], 2 scores [1,N], 3 count [1]
boxes = interpreter.get_tensor(output_info[0]["index"])[0]
classes = interpreter.get_tensor(output_info[1]["index"])[0]
scores = interpreter.get_tensor(output_info[2]["index"])[0]
count = int(interpreter.get_tensor(output_info[3]["index"])[0])
found = 0
for i in range(count):
score = float(scores[i])
if score < SCORE_THRESHOLD:
continue
class_id = int(classes[i])
label = labels[class_id] if class_id < len(labels) else f"id {class_id}"
ymin, xmin, ymax, xmax = boxes[i]
x1, y1 = max(0, int(xmin * img_w)), max(0, int(ymin * img_h))
x2, y2 = min(img_w - 1, int(xmax * img_w)), min(img_h - 1, int(ymax * img_h))
cv2.rectangle(image_bgr, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(image_bgr, f"{label} {score:.0%}", (x1, max(15, y1 - 6)),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
print(f"{label:>12}: {score:.2f} at ({x1},{y1})-({x2},{y2})")
found += 1
cv2.imwrite("detections.jpg", image_bgr)
print(f"{found} object(s) above {SCORE_THRESHOLD}; inference {infer_ms:.0f} ms")
if __name__ == "__main__":
main()ការពន្យល់៖ កូដនេះអាន Input Shape ពីម៉ូដែល (មិនសរសេរលេខរឹង) គាំទ្រទាំងម៉ូដែល uint8 និង float32 វាស់ពេល invoke() ហើយបម្លែង Normalized Boxes ទៅជា Pixel ដោយ Clamp កុំឱ្យលើសព្រំរូប។ លទ្ធផលត្រូវបានរក្សាទុកជា detections.jpg។
សំណួរវាស់សមត្ថភាព (Knowledge Check)
ឆ្លើយគ្រប់សំណួរ រួចចុច «ពិនិត្យចម្លើយ»។ បើត្រឹមត្រូវ ≥ ៨០% មេរៀននេះនឹងត្រូវបានកត់ត្រាថាបានបញ្ចប់ស្វ័យប្រវត្តិ។
- LiteRT — Run inference in Python ai.google.devឯកសារ Interpreter API (allocate_tensors, set_tensor, invoke, get_tensor)។
- LiteRT GitHub Repository github.com/google-ai-edgeកូដប្រភព និងការចេញផ្សាយកញ្ចប់ ai-edge-litert។