04 / Python
Python। মডেল থেকে ক্যামেরা পর্যন্ত।
লাইভ অ্যানোটেশন ও সীমিত ফ্রেম প্রসেসিংসহ আপনার ONNX ডিটেক্টর স্থানীয়ভাবে চালান।
উদাহরণগুলো নিয়ন্ত্রিত পরিবেশে বস্তু ও প্রাণী নিয়ে। মানুষের নজরদারি, পরিচয় শনাক্তকরণ বা আচরণ বিশ্লেষণ এর অন্তর্ভুক্ত নয়।
প্রকল্প তৈরি করুন
তালিকাভুক্ত নির্ভরতাগুলো ইনস্টল করুন এবং পরীক্ষাগুলো চালান। ক্যামেরা খোলার আগে একটি স্থানীয় ছবি দিয়ে চেষ্টা করুন।
মূল বিষয়
python -m unittest- ক্যামেরা না খুলেই স্বয়ংক্রিয় পরীক্ষা চালায়।
unzip badbob-playground-python.zip
cd badbob-playground-python
python3.12 -m venv .venv
. .venv/bin/activate
python -m pip install -r requirements.txt
python -m unittest discover -s tests -vমডেল যুক্ত করুন
ক্যামেরা খোলার আগে মডেল ও লেবেল যাচাই করুন।
মূল বিষয়
OnnxDetector.__init__(...)- ONNX মডেল লোড করে এবং ইনপুট, আউটপুট ও লেবেলের সংখ্যা যাচাই করে।
prepare_input(...)- অনুপাত বজায় রেখে 640×640 আকারের RGB ইনপুট তৈরি করে এবং বাকি অংশ পূরণ করে।
OnnxDetector.detect(...)- ছবি প্রস্তুত করে, মডেল চালায় এবং শনাক্তকরণের ফল ফেরত দেয়।
মনে রাখুন
- লক্ষণ
- বক্স সরে যায় অথবা মডেল লোড হয় না।
- কারণ
- প্রিপ্রসেসিং, আউটপুট বিন্যাস বা লেবেলের ক্রম মেলে না।
- সমাধান
- এই অ্যাডাপ্টার শুধু নিচের চুক্তিটি সমর্থন করে। Core ML ফাইল ও অন্য ONNX আউটপুট বিন্যাসের জন্য আলাদা অ্যাডাপ্টার লাগে।
এই অ্যাডাপ্টার শুধু নিচের চুক্তিটি সমর্থন করে। Core ML ফাইল ও অন্য ONNX আউটপুট বিন্যাসের জন্য আলাদা অ্যাডাপ্টার লাগে।
বিস্তারিত
স্থানাঙ্ক 640×640 ইনপুট পিক্সেলে বক্সের কেন্দ্র ও আকার বোঝায়। লেবেলগুলো অবশ্যই মডেলের ক্লাসের সঠিক ক্রমে থাকতে হবে।
input:
color: RGB
dtype: float32
shape: [1, 3, 640, 640]
letterbox: 114
scale: 1/255
output:
dtype: float32
shape: [1, 4+C, N]
boxes: [cx, cy, width, height]
class_scores: probabilities
objectness: false
embedded_nms: false"""Explicit CPU ONNX adapter; another export contract needs another adapter."""
from pathlib import Path
from typing import cast
import cv2
import numpy as np
import onnxruntime as ort
from .geometry import calculate_letterbox, decode_predictions
from .image_contract import validate_image
from .labels import validate_label_metadata
from .types import Detection, Image, Letterbox, Tensor
def prepare_input(frame: Image) -> tuple[Tensor, Letterbox]:
validate_image(frame)
transform = calculate_letterbox(frame.shape[1], frame.shape[0])
resized = cv2.resize(frame, (transform.width, transform.height), interpolation=cv2.INTER_LINEAR)
canvas = np.full((640, 640, 3), 114, dtype=np.uint8)
canvas[
transform.top : transform.top + transform.height,
transform.left : transform.left + transform.width,
] = resized
rgb = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
tensor = np.ascontiguousarray(rgb.transpose(2, 0, 1)[None], dtype=np.float32)
tensor /= np.float32(255)
return tensor, transform
class OnnxDetector:
def __init__(self, model: Path, labels: tuple[str, ...]) -> None:
if not model.is_file() or model.suffix.lower() != ".onnx":
raise ValueError("Supply an existing local .onnx model")
if not 1 <= len(labels) <= 1024:
raise ValueError("Expected 1..1024 class labels")
self._session: ort.InferenceSession | None = None
self._classes = len(labels)
ort.disable_telemetry_events()
session = ort.InferenceSession(str(model), providers=["CPUExecutionProvider"])
inputs, outputs = session.get_inputs(), session.get_outputs()
if (
len(inputs) != 1
or inputs[0].type != "tensor(float)"
or inputs[0].shape != [1, 3, 640, 640]
):
raise ValueError("Expected one float32 RGB NCHW input [1,3,640,640]")
if len(outputs) != 1 or outputs[0].type != "tensor(float)":
raise ValueError("Expected one float32 detector output")
self._validate_output_shape(outputs[0].shape)
validate_label_metadata(session.get_modelmeta().custom_metadata_map, labels)
self._input_name, self._output_name = inputs[0].name, outputs[0].name
self._session = session
# Validate actual output values before the runner may acquire a camera.
self.detect(np.full((640, 640, 3), 114, dtype=np.uint8))
def _validate_output_shape(self, shape: object) -> None:
if not isinstance(shape, list) or len(shape) != 3 or shape[:2] != [1, 4 + self._classes]:
raise ValueError("Expected output metadata [1,4+C,N] matching label count")
candidates = shape[2]
if isinstance(candidates, int) and not 1 <= candidates <= 100000:
raise ValueError("Expected 1..100000 detector candidates")
if candidates is not None and not isinstance(candidates, (str, int)):
raise ValueError("Invalid detector candidate dimension")
def detect(self, frame: Image) -> tuple[Detection, ...]:
session = self._session
if session is None:
raise RuntimeError("Detector is closed")
tensor, transform = prepare_input(frame)
results = session.run([self._output_name], {self._input_name: tensor})
output: object = results[0]
if not isinstance(output, np.ndarray) or output.dtype != np.float32:
raise ValueError("Expected a float32 NumPy detector tensor")
return decode_predictions(cast(Tensor, output), self._classes, transform)
def close(self) -> None:
# The Python CPU session has no public close(); drop its owner reference.
self._session = Noneক্যামেরা যুক্ত করুন
ক্যাপচার ও ইনফারেন্স একই ক্রমিক ওয়ার্কার থ্রেডে চলে। ইন্টারফেস শুধু সর্বশেষ সম্পূর্ণ প্রসেস করা ছবি ও তার শনাক্তকরণ পায়।
মূল বিষয়
Runner._run()- একটি ওয়ার্কার থ্রেডে ছবি গ্রহণ ও ইনফারেন্স পরিচালনা করে।
LatestResult.take()- সর্বশেষ সম্পূর্ণ প্রক্রিয়াকৃত ছবি ও তার শনাক্তকরণ নেয়; ফলাফল সারিতে জমতে পারে না।
Runner.stop()- নতুন ফলাফল গ্রহণ বন্ধ করে এবং চলমান কাজ শেষ হলে সম্পদ মুক্ত করে।
মনে রাখুন
- লক্ষণ
- প্রিভিউ পিছিয়ে পড়ে এবং মেমোরির ব্যবহার বাড়ে।
- কারণ
- ইনফারেন্স যত দ্রুত ফ্রেম প্রক্রিয়া করে, ক্যামেরা তার চেয়ে দ্রুত ফ্রেম দেয়, ফলে সীমাহীন সারি বাড়তে থাকে।
- সমাধান
- ক্যাপচার ও ইনফারেন্স একই ক্রমিক ওয়ার্কার থ্রেডে চলে। ইন্টারফেস শুধু সর্বশেষ সম্পূর্ণ প্রসেস করা ছবি ও তার শনাক্তকরণ পায়।
বিস্তারিত
বন্ধ করার অনুরোধ করুন, দেরিতে আসা ফলাফল বাতিল করুন এবং সম্পদ মুক্ত করার আগে চলমান কাজ শেষ হওয়ার অপেক্ষা করুন। অন্তর্নিহিত ব্যবস্থায় কাজ বাতিল করা প্ল্যাটফর্মের সমর্থনের ওপর নির্ভর করে।
"""One joined worker, no input queue, and one complete owned output pair."""
import threading
from collections.abc import Callable
from .types import Detector, FrameResult, FrameSource
class LatestResult:
def __init__(self) -> None:
self._lock = threading.Lock()
self._pending: FrameResult | None = None
self._closed = False
def publish(self, result: FrameResult) -> bool:
with self._lock:
if self._closed:
return False
self._pending = result
return True
def take(self) -> FrameResult | None:
with self._lock:
result, self._pending = self._pending, None
return result
def close(self) -> None:
with self._lock:
self._closed = True
self._pending = None
class Runner:
def __init__(
self, detector_factory: Callable[[], Detector], source_factory: Callable[[], FrameSource]
):
self.results = LatestResult()
self.finished = threading.Event()
self.stop_requested = threading.Event()
self.error: str | None = None
self._detector_factory = detector_factory
self._source_factory = source_factory
self._thread: threading.Thread | None = None
def start(self) -> None:
if self._thread is not None or self.stop_requested.is_set():
raise RuntimeError("A Runner starts once; create a new Runner for another session")
self._thread = threading.Thread(target=self._run, name="badbob-inference", daemon=False)
self._thread.start()
def stop(self) -> None:
self.stop_requested.set()
self.results.close()
if self._thread is not None:
self._thread.join()
def _capture(self, detector: Detector, source: FrameSource) -> None:
sequence = 0
while not self.stop_requested.is_set():
frame = source.read()
if frame is None:
return
if self.stop_requested.is_set():
return
# Own the pixels even when a backend or test double reuses its buffer.
owned_frame = frame.copy()
detections = detector.detect(owned_frame)
if self.stop_requested.is_set():
return
sequence += 1
self.results.publish(FrameResult(owned_frame, detections, sequence))
def _run(self) -> None:
detector: Detector | None = None
source: FrameSource | None = None
try:
detector = self._detector_factory()
if self.stop_requested.is_set():
return
source = self._source_factory()
self._capture(detector, source)
except Exception as error:
self.error = f"{type(error).__name__}: {error}"
self.results.close()
finally:
self._release(source, detector)
self.finished.set()
def _release(self, source: FrameSource | None, detector: Detector | None) -> None:
for resource in (source, detector):
if resource is None:
continue
try:
resource.close()
except Exception as error:
self.error = self.error or f"Cleanup failed: {error}"
self.results.close()পূর্বাভাস সঠিক স্থানে বসান
letterbox স্কেলিং ও প্যাডিং ফিরিয়ে নিন, তারপর আঁকার আগে বক্সগুলো ছবির সীমানায় সীমিত করুন।
মূল বিষয়
calculate_letterbox(...) · unproject_box(...)- ছবির অনুপাত বজায় রাখে এবং বক্সকে মূল ছবির স্থানাঙ্কে ফিরিয়ে আনে।
decode_predictions(...)- পূর্বাভাস যাচাই করে এবং একই ক্লাসের ওভারল্যাপ করা বক্স সরায়।
মনে রাখুন
ছবির মাপ, ক্রপ, অভিমুখ ও স্থানাঙ্ককে একটিই চুক্তি হিসেবে ধরুন। চিহ্নে ভরসা করার আগে পরিচিত বাক্স দিয়ে পরীক্ষা করুন।
"""Letterbox geometry and bounded class-aware suppression."""
import math
import numpy as np
from .types import Box, Detection, Letterbox, Tensor
def calculate_letterbox(width: int, height: int, edge: int = 640) -> Letterbox:
if width <= 0 or height <= 0 or not 0 < edge <= 4096:
raise ValueError("Positive image dimensions and input edge <=4096 required")
scale = min(edge / width, edge / height)
resized_width = max(1, math.floor(width * scale + 0.5))
resized_height = max(1, math.floor(height * scale + 0.5))
return Letterbox(
width,
height,
resized_width,
resized_height,
(edge - resized_width) // 2,
(edge - resized_height) // 2,
edge,
)
def validate_transform(transform: Letterbox) -> None:
if (
transform.original_width <= 0
or transform.original_height <= 0
or not 0 < transform.width <= transform.edge <= 4096
or not 0 < transform.height <= transform.edge
or not 0 <= transform.left <= transform.edge - transform.width
or not 0 <= transform.top <= transform.edge - transform.height
):
raise ValueError("Invalid letterbox geometry")
def unproject_box(box: Box, transform: Letterbox) -> Box:
validate_transform(transform)
values = (box.x, box.y, box.width, box.height, box.x + box.width, box.y + box.height)
if not all(math.isfinite(value) for value in values) or min(box.width, box.height) < 0:
raise ValueError("Box coordinates must be finite with nonnegative dimensions")
def x(value: float) -> float:
return (
min(1.0, max(0.0, (value - transform.left) / transform.width))
* transform.original_width
)
def y(value: float) -> float:
return (
min(1.0, max(0.0, (value - transform.top) / transform.height))
* transform.original_height
)
left, top = x(box.x), y(box.y)
return Box(left, top, x(box.x + box.width) - left, y(box.y + box.height) - top)
def intersection_over_union(first: Box, second: Box) -> float:
width = max(0.0, min(first.x + first.width, second.x + second.width) - max(first.x, second.x))
height = max(
0.0, min(first.y + first.height, second.y + second.height) - max(first.y, second.y)
)
intersection = width * height
union = first.width * first.height + second.width * second.height - intersection
return intersection / union if union > 0 else 0.0
def validate_predictions(data: Tensor, classes: int, confidence: float, overlap: float) -> None:
if (
data.dtype != np.float32
or data.ndim != 3
or not 1 <= classes <= 1024
or data.shape[:2] != (1, 4 + classes)
or not 1 <= data.shape[2] <= 100000
):
raise ValueError("Expected float32 [1,4+C,N], C<=1024 and 1<=N<=100000")
if not all(math.isfinite(value) and 0 <= value <= 1 for value in (confidence, overlap)):
raise ValueError("Confidence and overlap must be finite probabilities in [0,1]")
if not np.isfinite(data).all() or (data[0, 2:4] < 0).any():
raise ValueError("Unsupported detector coordinates: finite nonnegative sizes required")
if (data[0, 4:] < 0).any() or (data[0, 4:] > 1).any():
raise ValueError("Expected class probabilities in [0,1], not logits/objectness")
def decode_predictions(
data: Tensor,
classes: int,
transform: Letterbox,
confidence: float = 0.25,
overlap: float = 0.45,
) -> tuple[Detection, ...]:
validate_transform(transform)
validate_predictions(data, classes, confidence, overlap)
labels = np.argmax(data[0, 4:], axis=0)
scores = np.max(data[0, 4:], axis=0)
indices = np.flatnonzero(scores >= confidence)
indices = indices[np.argsort(-scores[indices], kind="stable")]
candidates: list[Detection] = []
for index in indices:
cx, cy, width, height = (float(value) for value in data[0, :4, index])
box = unproject_box(Box(cx - width / 2, cy - height / 2, width, height), transform)
if box.width <= 0 or box.height <= 0:
continue
candidates.append(Detection(box, int(labels[index]), float(scores[index])))
if len(candidates) == 3000:
break
return suppress_overlaps(candidates, overlap)
def suppress_overlaps(candidates: list[Detection], overlap: float) -> tuple[Detection, ...]:
selected: list[Detection] = []
for candidate in candidates:
if any(
previous.label == candidate.label
and intersection_over_union(previous.box, candidate.box) > overlap
for previous in selected
):
continue
selected.append(candidate)
if len(selected) == 300:
break
return tuple(selected)বিল্ড করুন। চালান। পরীক্ষা করুন।
ক্যামেরা স্পষ্টভাবে বেছে নিন অথবা অফলাইনে ছবি প্রসেস করুন। থামাতে Q বা Escape চাপুন।
মূল বিষয়
parse_options(...)- আর্গুমেন্ট যাচাই করে এবং ঠিক একটি ইনপুট বেছে নেয়: ছবি বা ক্যামেরা।
main(...)- নির্বাচিত উৎস যাচাই করে এবং ছবি বা ক্যামেরার প্রক্রিয়াকরণ সংশ্লিষ্ট অংশের কাছে পাঠায়।
মনে রাখুন
- লক্ষণ
- থামতে প্রত্যাশার চেয়ে বেশি সময় লাগছে।
- কারণ
- ছবি সংগ্রহ বা অনুমানের কোনো নেটিভ কল এখনো চলছে।
- সমাধান
- বন্ধ করার অনুরোধ করুন, দেরিতে আসা ফলাফল বাতিল করুন এবং সম্পদ মুক্ত করার আগে চলমান কাজ শেষ হওয়ার অপেক্ষা করুন। অন্তর্নিহিত ব্যবস্থায় কাজ বাতিল করা প্ল্যাটফর্মের সমর্থনের ওপর নির্ভর করে।
python -m badbob_camera --model detector.onnx --labels labels.txt --image frame.png --output result.png
python -m badbob_camera --model detector.onnx --labels labels.txt --camera 004.06 / ভালো চর্চা
ছোট খুঁটিনাটি। ভালো উদাহরণ।
- ক্যাপচার ও ইনফারেন্স UI থ্রেডের বাইরে রাখুন। পুরোনো ফ্রেম জমতে না দিয়ে সারির সীমা নির্ধারণ করুন।
- ছবির মাপ, ক্রপ, অভিমুখ ও স্থানাঙ্ককে একটিই চুক্তি হিসেবে ধরুন। চিহ্নে ভরসা করার আগে পরিচিত বাক্স দিয়ে পরীক্ষা করুন।
- বন্ধ করার অনুরোধ করুন, দেরিতে আসা ফলাফল বাতিল করুন এবং সম্পদ মুক্ত করার আগে চলমান কাজ শেষ হওয়ার অপেক্ষা করুন। অন্তর্নিহিত ব্যবস্থায় কাজ বাতিল করা প্ল্যাটফর্মের সমর্থনের ওপর নির্ভর করে।