File size: 3,756 Bytes
0e0cc3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
"""Tune sample1 detection toward 1500+ pipes."""
from __future__ import annotations

import cv2
import numpy as np
import onnxruntime as ort
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
IMG = Path(r"C:\Work\pipecountappv2026\sample1.jpg")


def letterbox(im: np.ndarray, size: int):
    ih, iw = im.shape[:2]
    scale = min(size / iw, size / ih)
    nw = max(1, min(size, int(round(iw * scale))))
    nh = max(1, min(size, int(round(ih * scale))))
    px, py = (size - nw) // 2, (size - nh) // 2
    out = np.full((size, size, 3), 114, dtype=np.uint8)
    out[py : py + nh, px : px + nw] = cv2.resize(im, (nw, nh), interpolation=cv2.INTER_AREA)
    tensor = np.transpose(out[:, :, ::-1].astype(np.float32) / 255, (2, 0, 1))[None, ...]
    return tensor, scale, px, py


def box_iou(a, b):
    x1, y1 = max(a[0], b[0]), max(a[1], b[1])
    x2, y2 = min(a[2], b[2]), min(a[3], b[3])
    inter = max(0, x2 - x1) * max(0, y2 - y1)
    aa = (a[2] - a[0]) * (a[3] - a[1])
    bb = (b[2] - b[0]) * (b[3] - b[1])
    return inter / (aa + bb - inter + 1e-6)


def nms(boxes, scores, thr=0.45, max_det=4000):
    order = np.argsort(scores)[::-1]
    keep = []
    while order.size and len(keep) < max_det:
        i = order[0]
        keep.append(i)
        if order.size == 1:
            break
        rest = order[1:]
        ious = np.array([box_iou(boxes[i], boxes[j]) for j in rest])
        order = rest[ious <= thr]
    return keep


def run_tiled(session, img, grid, conf, overlap, iou_thr):
    h, w = img.shape[:2]
    all_boxes, all_scores = [], []
    tw, th = w / grid, h / grid
    for gy in range(grid):
        for gx in range(grid):
            x1 = max(0, gx * tw - (tw * overlap if gx else 0))
            y1 = max(0, gy * th - (th * overlap if gy else 0))
            x2 = min(w, (gx + 1) * tw + (tw * overlap if gx < grid - 1 else 0))
            y2 = min(h, (gy + 1) * th + (th * overlap if gy < grid - 1 else 0))
            crop = img[int(y1) : int(y2), int(x1) : int(x2)]
            if crop.size == 0:
                continue
            tensor, scale, px, py = letterbox(crop, 1024)
            out = session.run(None, {"images": tensor})[0]
            for cx, cy, bw, bh, obj, cls in out.reshape(-1, 6):
                c = float(obj * cls)
                if c < conf:
                    continue
                bx1 = (cx - bw / 2 - px) / scale + x1
                by1 = (cy - bh / 2 - py) / scale + y1
                bx2 = (cx + bw / 2 - px) / scale + x1
                by2 = (cy + bh / 2 - py) / scale + y1
                bx1, by1 = max(0, bx1), max(0, by1)
                bx2, by2 = min(w, bx2), min(h, by2)
                if bx2 <= bx1 or by2 <= by1:
                    continue
                all_boxes.append([bx1, by1, bx2, by2])
                all_scores.append(c)
    return len(nms(all_boxes, all_scores, iou_thr))


def main():
    img = cv2.imread(str(IMG))
    h, w = img.shape[:2]
    session = ort.InferenceSession(
        str(ROOT / "static/models/countmodel.onnx"),
        providers=["CPUExecutionProvider"],
    )
    print(f"sample1 {w}x{h} target 1500+")
    best = []
    for grid in [1, 2, 3, 4, 5]:
        for conf in [0.15, 0.2, 0.25, 0.3]:
            for overlap in [0.15, 0.2, 0.25]:
                for iou in [0.35, 0.4, 0.45]:
                    c = run_tiled(session, img, grid, conf, overlap, iou)
                    best.append((abs(c - 1500), c, grid, conf, overlap, iou))
    best.sort(key=lambda x: x[0])
    print("Top 10 closest to 1500:")
    for row in best[:10]:
        diff, c, grid, conf, overlap, iou = row
        print(f"  count={c} (diff {c-1500:+d}) grid={grid} conf={conf} overlap={overlap} iou={iou}")


if __name__ == "__main__":
    main()