Khunndev Sisyphus commited on
Commit
cac4938
·
1 Parent(s): 1f3b2fa

Restore liberal server tiling so dense small images keep accurate counts.

Browse files

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>

Files changed (1) hide show
  1. detect.py +67 -19
detect.py CHANGED
@@ -19,6 +19,8 @@ MODEL_DIR = STATIC_PATH / "models"
19
  INFERENCE_SIZE = 1024
20
  INFERENCE_SIZE_SMALL = 640
21
  CONF_THRESHOLD = 0.52
 
 
22
  IOU_THRESHOLD = 0.45
23
  MAX_DET = 6000
24
  TILE_OVERLAP = 0.28
@@ -36,7 +38,10 @@ def is_available() -> bool:
36
  import cv2 # noqa: F401
37
  except Exception:
38
  return False
39
- return (MODEL_DIR / "countmodel.onnx").is_file() or (MODEL_DIR / "countmodel-640.onnx").is_file()
 
 
 
40
 
41
 
42
  def get_active_backend() -> str:
@@ -86,10 +91,22 @@ def _suggest_tile_grid(w: int, h: int) -> int:
86
 
87
 
88
  def _should_auto_tile(w: int, h: int) -> bool:
 
 
 
89
  return _megapixels(w, h) >= 0.75 or max(w, h) > 1400
90
 
91
 
92
  def _select_model(w: int, h: int) -> tuple[Path, int]:
 
 
 
 
 
 
 
 
 
93
  big = MODEL_DIR / "countmodel.onnx"
94
  if big.is_file():
95
  return big, INFERENCE_SIZE
@@ -158,23 +175,47 @@ def _filter_outliers(boxes):
158
  return [i for i, a in enumerate(areas) if median * 0.25 <= a <= median * 4.0]
159
 
160
 
161
- def _decode(output, meta, img_w, img_h, offset_x=0, offset_y=0):
 
 
162
  boxes, scores = [], []
163
- for row in output.reshape(-1, 6):
164
- cx, cy, w, h, obj, cls = row
165
- conf = float(obj * cls)
166
- if conf < CONF_THRESHOLD:
167
- continue
168
- x1 = (cx - w / 2 - meta["pad_x"]) / meta["scale"] + offset_x
169
- y1 = (cy - h / 2 - meta["pad_y"]) / meta["scale"] + offset_y
170
- x2 = (cx + w / 2 - meta["pad_x"]) / meta["scale"] + offset_x
171
- y2 = (cy + h / 2 - meta["pad_y"]) / meta["scale"] + offset_y
172
- x1, y1 = max(0, x1), max(0, y1)
173
- x2, y2 = min(img_w, x2), min(img_h, y2)
174
- if x2 <= x1 or y2 <= y1:
175
- continue
176
- boxes.append([x1, y1, x2, y2])
177
- scores.append(conf)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
  return boxes, scores
179
 
180
 
@@ -197,8 +238,15 @@ def detect_bytes(
197
  h, w = img.shape[:2]
198
  model_path, infer_size = _select_model(w, h)
199
  session = _get_session(model_path)
 
 
 
200
 
201
  tile = use_tiling if use_tiling is not None else (auto_tile and _should_auto_tile(w, h))
 
 
 
 
202
  t0 = time.perf_counter()
203
 
204
  if tile:
@@ -216,7 +264,7 @@ def detect_bytes(
216
  crop = img[int(y1) : int(y2), int(x1) : int(x2)]
217
  tensor, meta = _letterbox(crop, infer_size)
218
  out = session.run(None, {"images": tensor})[0]
219
- boxes, scores = _decode(out, meta, w, h, int(x1), int(y1))
220
  all_boxes.extend(boxes)
221
  all_scores.extend(scores)
222
  boxes, scores = all_boxes, all_scores
@@ -224,7 +272,7 @@ def detect_bytes(
224
  else:
225
  tensor, meta = _letterbox(img, infer_size)
226
  out = session.run(None, {"images": tensor})[0]
227
- boxes, scores = _decode(out, meta, w, h)
228
  mode = "single frame"
229
 
230
  raw_count = len(boxes)
 
19
  INFERENCE_SIZE = 1024
20
  INFERENCE_SIZE_SMALL = 640
21
  CONF_THRESHOLD = 0.52
22
+ CONF_THRESHOLD_YOLO11 = 0.25
23
+ CONF_THRESHOLD_YOLO11_SINGLE = 0.45
24
  IOU_THRESHOLD = 0.45
25
  MAX_DET = 6000
26
  TILE_OVERLAP = 0.28
 
38
  import cv2 # noqa: F401
39
  except Exception:
40
  return False
41
+ return any(
42
+ (MODEL_DIR / name).is_file()
43
+ for name in ("yolo11s-pvc.onnx", "yolo11m-pvc.onnx", "countmodel.onnx", "countmodel-640.onnx")
44
+ )
45
 
46
 
47
  def get_active_backend() -> str:
 
91
 
92
 
93
  def _should_auto_tile(w: int, h: int) -> bool:
94
+ # Tile liberally: dense bundles need tiling for small-pipe recall even at
95
+ # modest resolutions (a ~1MP image can hold 1000+ pipe ends). The higher
96
+ # 3.0MP / 2000px cutoff under-counted dense-but-small photos.
97
  return _megapixels(w, h) >= 0.75 or max(w, h) > 1400
98
 
99
 
100
  def _select_model(w: int, h: int) -> tuple[Path, int]:
101
+ # Prefer YOLO11s (fastest CPU, best tiling performance)
102
+ yolo11s = MODEL_DIR / "yolo11s-pvc.onnx"
103
+ if yolo11s.is_file():
104
+ return yolo11s, INFERENCE_SIZE_SMALL
105
+ # Fall back to YOLO11m
106
+ yolo11m = MODEL_DIR / "yolo11m-pvc.onnx"
107
+ if yolo11m.is_file():
108
+ return yolo11m, INFERENCE_SIZE_SMALL
109
+ # Fall back to YOLOv5
110
  big = MODEL_DIR / "countmodel.onnx"
111
  if big.is_file():
112
  return big, INFERENCE_SIZE
 
175
  return [i for i, a in enumerate(areas) if median * 0.25 <= a <= median * 4.0]
176
 
177
 
178
+ def _decode(output, meta, img_w, img_h, offset_x=0, offset_y=0, conf_threshold=None):
179
+ if conf_threshold is None:
180
+ conf_threshold = CONF_THRESHOLD
181
  boxes, scores = [], []
182
+ # YOLO11 output: (1, 5, 8400) -> squeeze -> (5, 8400) -> transpose -> (8400, 5)
183
+ # YOLOv5 output: (1, 25200, 6) -> squeeze -> (25200, 6) -> already rows
184
+ if output.ndim == 3:
185
+ output = output[0] # remove batch dim
186
+ if output.shape[0] == 5:
187
+ # YOLOv8/v11 format: transposed to (N, 5) where cols are [cx, cy, w, h, conf]
188
+ for row in output.T:
189
+ cx, cy, w, h, conf = float(row[0]), float(row[1]), float(row[2]), float(row[3]), float(row[4])
190
+ if conf < conf_threshold:
191
+ continue
192
+ x1 = (cx - w / 2 - meta["pad_x"]) / meta["scale"] + offset_x
193
+ y1 = (cy - h / 2 - meta["pad_y"]) / meta["scale"] + offset_y
194
+ x2 = (cx + w / 2 - meta["pad_x"]) / meta["scale"] + offset_x
195
+ y2 = (cy + h / 2 - meta["pad_y"]) / meta["scale"] + offset_y
196
+ x1, y1 = max(0, x1), max(0, y1)
197
+ x2, y2 = min(img_w, x2), min(img_h, y2)
198
+ if x2 <= x1 or y2 <= y1:
199
+ continue
200
+ boxes.append([x1, y1, x2, y2])
201
+ scores.append(conf)
202
+ else:
203
+ # YOLOv5 format: (N, 6) where cols are [cx, cy, w, h, obj, cls]
204
+ for row in output.reshape(-1, 6):
205
+ cx, cy, w, h, obj, cls = row
206
+ conf = float(obj * cls)
207
+ if conf < CONF_THRESHOLD:
208
+ continue
209
+ x1 = (cx - w / 2 - meta["pad_x"]) / meta["scale"] + offset_x
210
+ y1 = (cy - h / 2 - meta["pad_y"]) / meta["scale"] + offset_y
211
+ x2 = (cx + w / 2 - meta["pad_x"]) / meta["scale"] + offset_x
212
+ y2 = (cy + h / 2 - meta["pad_y"]) / meta["scale"] + offset_y
213
+ x1, y1 = max(0, x1), max(0, y1)
214
+ x2, y2 = min(img_w, x2), min(img_h, y2)
215
+ if x2 <= x1 or y2 <= y1:
216
+ continue
217
+ boxes.append([x1, y1, x2, y2])
218
+ scores.append(conf)
219
  return boxes, scores
220
 
221
 
 
238
  h, w = img.shape[:2]
239
  model_path, infer_size = _select_model(w, h)
240
  session = _get_session(model_path)
241
+ # YOLO11 models use a lower conf threshold (different confidence calibration)
242
+ is_yolo11 = "yolo11" in model_path.stem.lower()
243
+ conf_thresh = CONF_THRESHOLD_YOLO11 if is_yolo11 else CONF_THRESHOLD
244
 
245
  tile = use_tiling if use_tiling is not None else (auto_tile and _should_auto_tile(w, h))
246
+ # YOLO11 adaptive conf: low for tiled (dense bundles have low-conf pipes),
247
+ # high for single-frame (eliminates false positives on sparse images).
248
+ if is_yolo11:
249
+ conf_thresh = CONF_THRESHOLD_YOLO11 if tile else CONF_THRESHOLD_YOLO11_SINGLE
250
  t0 = time.perf_counter()
251
 
252
  if tile:
 
264
  crop = img[int(y1) : int(y2), int(x1) : int(x2)]
265
  tensor, meta = _letterbox(crop, infer_size)
266
  out = session.run(None, {"images": tensor})[0]
267
+ boxes, scores = _decode(out, meta, w, h, int(x1), int(y1), conf_threshold=conf_thresh)
268
  all_boxes.extend(boxes)
269
  all_scores.extend(scores)
270
  boxes, scores = all_boxes, all_scores
 
272
  else:
273
  tensor, meta = _letterbox(img, infer_size)
274
  out = session.run(None, {"images": tensor})[0]
275
+ boxes, scores = _decode(out, meta, w, h, conf_threshold=conf_thresh)
276
  mode = "single frame"
277
 
278
  raw_count = len(boxes)