pipecountapp-dev / scripts /test_samples.py
Khunndev
Cursor
Light CountThings theme, settings drawer, and results dock UX.
d30af0c
Raw History Blame Contribute Delete
7.6 kB
"""Test ONNX pipe-count model on sample images (matches browser pipeline)."""
from __future__ import annotations
import sys
import time
from pathlib import Path
import cv2
import numpy as np
import onnxruntime as ort
from scripts.image_enhance import enhance_bgr
ROOT = Path(__file__).resolve().parents[1]
MODEL_DIR = ROOT / "frontend" / "public" / "models"
INFERENCE_SIZE = 1024
INFERENCE_SIZE_SMALL = 640
CONF_THRESHOLD = 0.72
IOU_THRESHOLD = 0.45
MAX_DET = 4000
TILE_OVERLAP = 0.2
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 >= 8:
return 5
if mp >= 4:
return 4
if mp >= 2:
return 3
return 2
def should_auto_tile(w: int, h: int) -> bool:
return megapixels(w, h) >= 2 or max(w, h) > 2000
def select_model(w: int, h: int) -> tuple[Path, int]:
if max(w, h) <= 1200:
p = MODEL_DIR / "countmodel-640.onnx"
if p.is_file():
return p, INFERENCE_SIZE_SMALL
return MODEL_DIR / "countmodel.onnx", INFERENCE_SIZE
def letterbox(img: np.ndarray, size: int):
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, ...]
meta = {"scale": scale, "pad_x": pad_x, "pad_y": pad_y}
return chw, meta
def iou(a, b):
x1 = max(a[0], b[0])
y1 = max(a[1], b[1])
x2 = min(a[2], b[2])
y2 = min(a[3], b[3])
inter = max(0, x2 - x1) * max(0, y2 - y1)
area_a = (a[2] - a[0]) * (a[3] - a[1])
area_b = (b[2] - b[0]) * (b[3] - b[1])
return inter / (area_a + area_b - inter + 1e-6)
def nms(boxes, scores, iou_thres=IOU_THRESHOLD, max_det=MAX_DET):
order = np.argsort(scores)[::-1]
keep = []
while order.size > 0 and len(keep) < max_det:
i = order[0]
keep.append(i)
if order.size == 1:
break
rest = order[1:]
ious = np.array([iou(boxes[i], boxes[j]) for j in rest])
order = rest[ious <= iou_thres]
return keep
def filter_outliers(boxes):
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: np.ndarray, meta: dict, img_w: int, img_h: int, offset_x=0, offset_y=0, use_outliers=False):
boxes, scores = [], []
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)
if not boxes:
return [], []
idx = nms(boxes, scores)
boxes = [boxes[i] for i in idx]
scores = [scores[i] for i in idx]
if use_outliers:
keep = filter_outliers(boxes)
boxes = [boxes[i] for i in keep]
scores = [scores[i] for i in keep]
return boxes, scores
def infer_tile(session, tile: np.ndarray, size: int, offset_x: int, offset_y: int, img_w: int, img_h: int, use_outliers: bool):
tensor, meta = letterbox(tile, size)
out = session.run(None, {"images": tensor})[0]
return decode(out, meta, img_w, img_h, offset_x, offset_y, use_outliers)
def run_on_image(
image_path: Path,
out_path: Path,
enhance: bool = True,
use_tiling: bool | None = None,
use_outliers: bool = False,
):
img = cv2.imread(str(image_path))
if img is None:
raise FileNotFoundError(image_path)
if enhance:
img = enhance_bgr(img)
h, w = img.shape[:2]
model_path, infer_size = select_model(w, h)
session = ort.InferenceSession(str(model_path), providers=["CPUExecutionProvider"])
tile = use_tiling if use_tiling is not None else should_auto_tile(w, h)
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)]
boxes, scores = infer_tile(
session, crop, infer_size, int(x1), int(y1), w, h, use_outliers
)
all_boxes.extend(boxes)
all_scores.extend(scores)
if all_boxes:
idx = nms(all_boxes, all_scores)
boxes = [all_boxes[i] for i in idx]
scores = [all_scores[i] for i in idx]
else:
boxes, 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, use_outliers=use_outliers)
mode = "single frame"
ms = (time.perf_counter() - t0) * 1000
vis = img.copy()
for i, (box, _sc) in enumerate(zip(boxes, scores), 1):
x1, y1, x2, y2 = map(int, box)
cx, cy = (x1 + x2) // 2, (y1 + y2) // 2
r = max(10, min(x2 - x1, y2 - y1) // 2)
cv2.circle(vis, (cx, cy), r, (0, 0, 255), 2)
if len(boxes) <= 500:
cv2.putText(vis, str(i), (cx - 8, cy + 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
cv2.putText(vis, f"Count: {len(boxes)}", (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 255, 0), 3)
cv2.imwrite(str(out_path), vis)
return len(boxes), ms, (w, h), infer_size, model_path.name, mode
def main():
images = [Path(p) for p in sys.argv[1:]] or [
Path(r"C:\Work\pipecountappv2026\sample1.jpg"),
Path(r"C:\Work\pipecountappv2026\sample2.jpg"),
]
out_dir = ROOT / "test-output"
out_dir.mkdir(exist_ok=True)
print("ONNX inference with enhance + auto-tiling (matches browser)")
print("-" * 60)
for img_path in images:
if not img_path.is_file():
print(f"SKIP (not found): {img_path}")
continue
out_path = out_dir / f"{img_path.stem}-result.jpg"
count, ms, size, infer_size, model_name, mode = run_on_image(img_path, out_path)
print(f"{img_path.name}")
print(f" Size: {size[0]}x{size[1]} px | model: {model_name} @ {infer_size} | {mode}")
print(f" Pipes detected: {count}")
print(f" Inference: {ms:.0f} ms")
print(f" Annotated: {out_path}")
print()
if __name__ == "__main__":
main()