pipecountapp-dev / detect.py
Khunndev
Sisyphus
Restore liberal server tiling so dense small images keep accurate counts.
cac4938
Raw History Blame Contribute Delete
11 kB
"""Server-side ONNX pipe detection (CPU).
Used as a fallback when a client device cannot load / run the in-browser model.
Mirrors the browser inference pipeline (letterbox -> ONNX -> decode -> NMS) so
results are consistent regardless of where inference runs.
"""
from __future__ import annotations
import os
from pathlib import Path
from threading import Lock
from typing import Any
from postprocess import apply_detection_postprocess, select_nms_iou
STATIC_PATH = Path(__file__).resolve().parent / "static"
MODEL_DIR = STATIC_PATH / "models"
INFERENCE_SIZE = 1024
INFERENCE_SIZE_SMALL = 640
CONF_THRESHOLD = 0.52
CONF_THRESHOLD_YOLO11 = 0.25
CONF_THRESHOLD_YOLO11_SINGLE = 0.45
IOU_THRESHOLD = 0.45
MAX_DET = 6000
TILE_OVERLAP = 0.28
_sessions: dict[str, Any] = {}
_session_lock = Lock()
_active_backend = "cpu"
def is_available() -> bool:
"""True when server-side inference can run (deps + model files present)."""
try:
import numpy # noqa: F401
import onnxruntime # noqa: F401
import cv2 # noqa: F401
except Exception:
return False
return any(
(MODEL_DIR / name).is_file()
for name in ("yolo11s-pvc.onnx", "yolo11m-pvc.onnx", "countmodel.onnx", "countmodel-640.onnx")
)
def get_active_backend() -> str:
return _active_backend
def _get_session(model_path: Path):
global _active_backend
key = str(model_path)
sess = _sessions.get(key)
if sess is not None:
return sess
with _session_lock:
sess = _sessions.get(key)
if sess is not None:
return sess
import onnxruntime as ort
opts = ort.SessionOptions()
cores = os.cpu_count() or 2
opts.intra_op_num_threads = max(1, min(8, cores))
opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
providers = ort.get_available_providers()
# Prefer GPU if present on the host, else CPU.
chosen = [p for p in ("CUDAExecutionProvider", "CPUExecutionProvider") if p in providers]
if not chosen:
chosen = ["CPUExecutionProvider"]
_active_backend = "cuda" if chosen[0] == "CUDAExecutionProvider" else "cpu"
sess = ort.InferenceSession(str(model_path), sess_options=opts, providers=chosen)
_sessions[key] = sess
return sess
def _megapixels(w: int, h: int) -> float:
return (w * h) / 1_000_000
def _suggest_tile_grid(w: int, h: int) -> int:
mp = _megapixels(w, h)
if mp >= 6:
return 5
if mp >= 3:
return 4
if mp >= 1.2:
return 3
return 2
def _should_auto_tile(w: int, h: int) -> bool:
# Tile liberally: dense bundles need tiling for small-pipe recall even at
# modest resolutions (a ~1MP image can hold 1000+ pipe ends). The higher
# 3.0MP / 2000px cutoff under-counted dense-but-small photos.
return _megapixels(w, h) >= 0.75 or max(w, h) > 1400
def _select_model(w: int, h: int) -> tuple[Path, int]:
# Prefer YOLO11s (fastest CPU, best tiling performance)
yolo11s = MODEL_DIR / "yolo11s-pvc.onnx"
if yolo11s.is_file():
return yolo11s, INFERENCE_SIZE_SMALL
# Fall back to YOLO11m
yolo11m = MODEL_DIR / "yolo11m-pvc.onnx"
if yolo11m.is_file():
return yolo11m, INFERENCE_SIZE_SMALL
# Fall back to YOLOv5
big = MODEL_DIR / "countmodel.onnx"
if big.is_file():
return big, INFERENCE_SIZE
return MODEL_DIR / "countmodel-640.onnx", INFERENCE_SIZE_SMALL
def _letterbox(img, size: int):
import cv2
import numpy as np
h, w = img.shape[:2]
scale = min(size / w, size / h)
new_w, new_h = int(round(w * scale)), int(round(h * scale))
pad_x = (size - new_w) // 2
pad_y = (size - new_h) // 2
out = np.full((size, size, 3), 114, dtype=np.uint8)
resized = cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_AREA)
out[pad_y : pad_y + new_h, pad_x : pad_x + new_w] = resized
tensor = out[:, :, ::-1].astype(np.float32) / 255.0
chw = np.transpose(tensor, (2, 0, 1))[None, ...]
return chw, {"scale": scale, "pad_x": pad_x, "pad_y": pad_y}
def _nms(boxes, scores, iou_thres=IOU_THRESHOLD, max_det=MAX_DET):
import numpy as np
if len(boxes) == 0:
return []
boxes_arr = np.asarray(boxes, dtype=np.float32)
scores_arr = np.asarray(scores, dtype=np.float32)
x1 = boxes_arr[:, 0]
y1 = boxes_arr[:, 1]
x2 = boxes_arr[:, 2]
y2 = boxes_arr[:, 3]
areas = (x2 - x1) * (y2 - y1)
order = scores_arr.argsort()[::-1]
keep: list[int] = []
while order.size > 0 and len(keep) < max_det:
i = int(order[0])
keep.append(i)
if order.size == 1:
break
rest = order[1:]
xx1 = np.maximum(x1[i], x1[rest])
yy1 = np.maximum(y1[i], y1[rest])
xx2 = np.minimum(x2[i], x2[rest])
yy2 = np.minimum(y2[i], y2[rest])
w = np.maximum(0.0, xx2 - xx1)
h = np.maximum(0.0, yy2 - yy1)
inter = w * h
iou = inter / (areas[i] + areas[rest] - inter + 1e-6)
order = rest[iou <= iou_thres]
return keep
def _filter_outliers(boxes):
import numpy as np
if len(boxes) < 3:
return list(range(len(boxes)))
areas = [(b[2] - b[0]) * (b[3] - b[1]) for b in boxes]
median = float(np.median(areas))
return [i for i, a in enumerate(areas) if median * 0.25 <= a <= median * 4.0]
def _decode(output, meta, img_w, img_h, offset_x=0, offset_y=0, conf_threshold=None):
if conf_threshold is None:
conf_threshold = CONF_THRESHOLD
boxes, scores = [], []
# YOLO11 output: (1, 5, 8400) -> squeeze -> (5, 8400) -> transpose -> (8400, 5)
# YOLOv5 output: (1, 25200, 6) -> squeeze -> (25200, 6) -> already rows
if output.ndim == 3:
output = output[0] # remove batch dim
if output.shape[0] == 5:
# YOLOv8/v11 format: transposed to (N, 5) where cols are [cx, cy, w, h, conf]
for row in output.T:
cx, cy, w, h, conf = float(row[0]), float(row[1]), float(row[2]), float(row[3]), float(row[4])
if conf < conf_threshold:
continue
x1 = (cx - w / 2 - meta["pad_x"]) / meta["scale"] + offset_x
y1 = (cy - h / 2 - meta["pad_y"]) / meta["scale"] + offset_y
x2 = (cx + w / 2 - meta["pad_x"]) / meta["scale"] + offset_x
y2 = (cy + h / 2 - meta["pad_y"]) / meta["scale"] + offset_y
x1, y1 = max(0, x1), max(0, y1)
x2, y2 = min(img_w, x2), min(img_h, y2)
if x2 <= x1 or y2 <= y1:
continue
boxes.append([x1, y1, x2, y2])
scores.append(conf)
else:
# YOLOv5 format: (N, 6) where cols are [cx, cy, w, h, obj, cls]
for row in output.reshape(-1, 6):
cx, cy, w, h, obj, cls = row
conf = float(obj * cls)
if conf < CONF_THRESHOLD:
continue
x1 = (cx - w / 2 - meta["pad_x"]) / meta["scale"] + offset_x
y1 = (cy - h / 2 - meta["pad_y"]) / meta["scale"] + offset_y
x2 = (cx + w / 2 - meta["pad_x"]) / meta["scale"] + offset_x
y2 = (cy + h / 2 - meta["pad_y"]) / meta["scale"] + offset_y
x1, y1 = max(0, x1), max(0, y1)
x2, y2 = min(img_w, x2), min(img_h, y2)
if x2 <= x1 or y2 <= y1:
continue
boxes.append([x1, y1, x2, y2])
scores.append(conf)
return boxes, scores
def detect_bytes(
image_bytes: bytes,
use_tiling: bool | None = None,
auto_tile: bool = True,
filter_outliers_flag: bool = False,
) -> dict[str, Any]:
import time
import cv2
import numpy as np
arr = np.frombuffer(image_bytes, dtype=np.uint8)
img = cv2.imdecode(arr, cv2.IMREAD_COLOR)
if img is None:
raise ValueError("Could not decode image")
h, w = img.shape[:2]
model_path, infer_size = _select_model(w, h)
session = _get_session(model_path)
# YOLO11 models use a lower conf threshold (different confidence calibration)
is_yolo11 = "yolo11" in model_path.stem.lower()
conf_thresh = CONF_THRESHOLD_YOLO11 if is_yolo11 else CONF_THRESHOLD
tile = use_tiling if use_tiling is not None else (auto_tile and _should_auto_tile(w, h))
# YOLO11 adaptive conf: low for tiled (dense bundles have low-conf pipes),
# high for single-frame (eliminates false positives on sparse images).
if is_yolo11:
conf_thresh = CONF_THRESHOLD_YOLO11 if tile else CONF_THRESHOLD_YOLO11_SINGLE
t0 = time.perf_counter()
if tile:
grid = _suggest_tile_grid(w, h)
tile_w = w / grid
tile_h = h / grid
all_boxes: list = []
all_scores: list = []
for gy in range(grid):
for gx in range(grid):
x1 = max(0, gx * tile_w - (tile_w * TILE_OVERLAP * (gx > 0)))
y1 = max(0, gy * tile_h - (tile_h * TILE_OVERLAP * (gy > 0)))
x2 = min(w, (gx + 1) * tile_w + (tile_w * TILE_OVERLAP * (gx < grid - 1)))
y2 = min(h, (gy + 1) * tile_h + (tile_h * TILE_OVERLAP * (gy < grid - 1)))
crop = img[int(y1) : int(y2), int(x1) : int(x2)]
tensor, meta = _letterbox(crop, infer_size)
out = session.run(None, {"images": tensor})[0]
boxes, scores = _decode(out, meta, w, h, int(x1), int(y1), conf_threshold=conf_thresh)
all_boxes.extend(boxes)
all_scores.extend(scores)
boxes, scores = all_boxes, all_scores
mode = f"tiling {grid}x{grid}"
else:
tensor, meta = _letterbox(img, infer_size)
out = session.run(None, {"images": tensor})[0]
boxes, scores = _decode(out, meta, w, h, conf_threshold=conf_thresh)
mode = "single frame"
raw_count = len(boxes)
keep = _nms(boxes, scores, iou_thres=select_nms_iou(len(boxes)))
boxes = [boxes[i] for i in keep]
scores = [scores[i] for i in keep]
post_nms_count = len(boxes)
boxes, scores, report = apply_detection_postprocess(
boxes,
scores,
extra_outlier_filter=filter_outliers_flag,
filter_outliers_fn=_filter_outliers,
was_tiled=tile,
)
report["raw"] = raw_count
report["after_nms"] = post_nms_count
report["removed_by_nms"] = raw_count - post_nms_count
report["tiling_used"] = bool(tile)
ms = (time.perf_counter() - t0) * 1000
detections = [
{
"xmin": float(b[0]),
"ymin": float(b[1]),
"xmax": float(b[2]),
"ymax": float(b[3]),
"confidence": float(s),
}
for b, s in zip(boxes, scores)
]
return {
"detections": detections,
"count": len(detections),
"width": w,
"height": h,
"ms": round(ms),
"model": model_path.name,
"mode": mode,
"backend": f"server-{get_active_backend()}",
"postprocess": report,
}