-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02_Segment_Scan_Objects.py
More file actions
1686 lines (1508 loc) · 61.8 KB
/
Copy path02_Segment_Scan_Objects.py
File metadata and controls
1686 lines (1508 loc) · 61.8 KB
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""02: Segment dark bug silhouettes from a Top-camera scan.
Usage:
python3 scripts/02_Segment_Scan_Objects.py scans/scan_YYYYMMDD_HHMMSS
Outputs:
<scan_dir>/objects/*.png
<scan_dir>/overlays/*.png
<scan_dir>/objects.csv
<scan_dir>/objects.jsonl
"""
from __future__ import annotations
import argparse
import csv
import json
import sys
import time
from datetime import datetime
from pathlib import Path
from typing import Any
SCRIPT_PATH = Path(__file__).resolve()
if SCRIPT_PATH.parent.name == "BugPicker" and SCRIPT_PATH.parent.parent.name == "scripts":
PROJECT_ROOT = SCRIPT_PATH.parents[2]
else:
PROJECT_ROOT = SCRIPT_PATH.parents[1]
SCRIPTS_DIR = SCRIPT_PATH.parent
PREFERRED_PYTHON = PROJECT_ROOT / ".venv/bin/python"
try:
import cv2
import numpy as np
except ModuleNotFoundError as exc:
missing = exc.name
if Path(sys.executable).resolve() != PREFERRED_PYTHON.resolve() and PREFERRED_PYTHON.exists():
import os
os.execv(str(PREFERRED_PYTHON), [str(PREFERRED_PYTHON), str(SCRIPT_PATH), *sys.argv[1:]])
install_command = (
f"{sys.executable} -m pip install -r {SCRIPTS_DIR / 'requirements.txt'}"
if (SCRIPTS_DIR / "requirements.txt").exists()
else f"{sys.executable} -m pip install numpy opencv-python"
)
print(
f"Missing Python package {missing!r} for interpreter:\n"
f" {sys.executable}\n"
f"Install dependencies with:\n"
f" {install_command}\n"
f"Or run with the OpenPnP venv:\n"
f" {PREFERRED_PYTHON} {SCRIPT_PATH} <scan_dir>",
file=sys.stderr,
)
raise SystemExit(2) from exc
MIN_AREA_PX = 80
MAX_AREA_FRACTION = 0.03
MAX_RECT_AREA_FRACTION = 0.02
MAX_SHORT_SIDE_FRACTION = 0.12
MAX_LONG_SIDE_FRACTION = 0.18
MIN_RECTANGULARITY = 0.02
MIN_ASPECT_RATIO = 0.20
MAX_ASPECT_RATIO = 5.00
MAX_INSIDE_MEAN_INTENSITY = 165
MIN_BACKGROUND_CONTRAST = 25
FIXED_DARK_THRESHOLD = 70
RESISTOR_MIN_AREA_PX = 180
RESISTOR_MAX_AREA_FRACTION = 0.01
RESISTOR_MAX_RECT_AREA_FRACTION = 0.012
RESISTOR_MAX_SHORT_SIDE_FRACTION = 0.08
RESISTOR_MAX_LONG_SIDE_FRACTION = 0.16
RESISTOR_MIN_RECTANGULARITY = 0.55
RESISTOR_MIN_ASPECT_RATIO = 1.15
RESISTOR_MAX_ASPECT_RATIO = 6.00
RESISTOR_MAX_INSIDE_MEAN_INTENSITY = 115
RESISTOR_MIN_BACKGROUND_CONTRAST = 22
CLOSE_KERNEL_SIZE = 13
OPEN_KERNEL_SIZE = 2
PINK_MIN_SATURATION = 60
PINK_MIN_VALUE = 135
PINK_DILATE_KERNEL_SIZE = 15
PINK_RED_DOMINANCE = 12
PINK_MIN_HUE = 135
BUG_MIN_FILL_RATIO = 0.04
IMAGE_EDGE_REJECT_MARGIN_PX = 40
COLOR_PRESENT_SATURATION_P99 = 20
COLOR_MIN_AREA_PX = 1500
COLOR_MAX_AXIS_ASPECT_RATIO = 3.5
COLOR_MAX_INSIDE_MEAN_INTENSITY = 170
COLOR_MIN_RECTANGULARITY = 0.20
COLOR_MAX_SHORT_SIDE_FRACTION = 0.42
COLOR_MAX_LONG_SIDE_FRACTION = 0.48
COLOR_MIN_BACKGROUND_CONTRAST = -15
COLOR_MIN_USEFUL_CONTRAST = 8
COLOR_MAX_LOW_CONTRAST_MEAN_INTENSITY = 140
BUG_OUTLINE_MIN_AREA_PX = 3000
BUG_OUTLINE_MAX_INSIDE_MEAN_INTENSITY = 170
BUG_OUTLINE_MIN_ABS_CONTRAST = 10
BUG_BRIGHT_MIN_AREA_PX = 1500
BUG_BRIGHT_RESIDUAL_THRESHOLD = 13
BUG_BRIGHT_MIN_ABS_CONTRAST = 12
BUG_BODY_COLOR_MIN_AREA_PX = 1200
BUG_BODY_COLOR_MIN_ABS_CONTRAST = 7
GLOBAL_DEDUPE_DISTANCE_MM = 3.0
CONTEXT_PADDING_PX = 900
COORDINATE_TRANSFORM_VERSION = "image_y_inverted_v2"
GRAYSCALE_MIN_AREA_PX = 1000
GRAYSCALE_MIN_AXIS_ASPECT_RATIO = 1.9
GRAYSCALE_MAX_INSIDE_MEAN_INTENSITY = 55
GRAYSCALE_MIN_RECTANGULARITY = 0.55
EDGE_MIN_AREA_PX = 1200
EDGE_MIN_RECTANGULARITY = 0.42
EDGE_MIN_ASPECT_RATIO = 1.20
EDGE_MAX_ASPECT_RATIO = 5.00
EDGE_MIN_ABS_CONTRAST = 6
EDGE_CANNY_LOW = 18
EDGE_CANNY_HIGH = 55
BOUNDING_BOX_COLOR = (0, 255, 0)
DUPLICATE_BOX_COLOR = (0, 165, 255)
CENTROID_COLOR = (0, 0, 255)
LABEL_COLOR = (255, 255, 255)
LABEL_BACKGROUND_COLOR = (0, 128, 0)
DUPLICATE_LABEL_BACKGROUND_COLOR = (0, 100, 220)
LINE_THICKNESS = 2
CENTROID_MARK_SIZE = 10
CONTROL_DIR = PROJECT_ROOT / "control"
DETECTION_STATUS_FILE = CONTROL_DIR / "detection_status.json"
DETECTION_PREVIEW_FILE = CONTROL_DIR / "latest_detection_overlay.png"
TRAINING_TRAY_CALIBRATION_FILE = SCRIPTS_DIR / "training_tray_calibration.json"
CONTROL_TRAINING_TRAY_CALIBRATION_FILE = CONTROL_DIR / "training_tray_calibration.json"
PREVIEW_MAX_WIDTH = 520
PREVIEW_MAX_HEIGHT = 293
DEFAULT_TRAINING_TRAY_CALIBRATION: dict[str, float] = {
"x_left_mm": 361.0,
"x_right_mm": 411.0,
"y_top_mm": 208.0,
"y_bottom_mm": 319.0,
"camera_x_offset_mm": -23.0,
"camera_y_offset_mm": 64.0,
"x_step_mm": 8.0,
"y_step_mm": 5.0,
}
def write_detection_status(scan_dir: Path, status: str, **values: Any) -> None:
CONTROL_DIR.mkdir(exist_ok=True)
payload: dict[str, Any] = {
"status": status,
"scan_dir": str(scan_dir),
"updated_at": datetime.now().isoformat(),
}
payload.update(values)
DETECTION_STATUS_FILE.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
def write_segmentation_complete(
scan_dir: Path,
object_count: int,
processed_count: int,
candidate_count: int,
duplicate_count: int,
summary_file: str | None,
detector: str,
calibration: dict[str, Any],
) -> None:
complete_path = scan_dir / "segmentation_complete.json"
payload = {
"status": "completed",
"scan_dir": str(scan_dir),
"object_count": object_count,
"detector": detector,
"candidate_count": candidate_count,
"duplicate_count": duplicate_count,
"summary_file": summary_file,
"training_tray_calibration_source": calibration.get("source"),
"processed_frame_count": processed_count,
"updated_at": datetime.now().isoformat(),
}
complete_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
def load_training_tray_calibration(calibration_path: Path | None = None) -> dict[str, Any]:
calibration: dict[str, Any] = dict(DEFAULT_TRAINING_TRAY_CALIBRATION)
source = "built-in defaults"
candidates = []
if calibration_path is not None:
candidates.append(calibration_path)
candidates.extend([TRAINING_TRAY_CALIBRATION_FILE, CONTROL_TRAINING_TRAY_CALIBRATION_FILE])
for candidate in candidates:
if not candidate.exists():
continue
data = json.loads(candidate.read_text(encoding="utf-8"))
for key, fallback in DEFAULT_TRAINING_TRAY_CALIBRATION.items():
value = data.get(key, fallback)
try:
calibration[key] = float(value)
except (TypeError, ValueError) as exc:
raise ValueError(f"Calibration value is not numeric: {key}={value!r}") from exc
source = str(candidate)
break
calibration["source"] = source
return calibration
def normalize_manifest_frame(frame: dict[str, Any], calibration: dict[str, Any]) -> dict[str, Any]:
normalized = dict(frame)
camera_x_offset = float(calibration["camera_x_offset_mm"])
camera_y_offset = float(calibration["camera_y_offset_mm"])
if "x_mm" not in normalized and "requested_x_mm" in normalized:
normalized["x_mm"] = float(normalized["requested_x_mm"]) + camera_x_offset
if "y_mm" not in normalized and "requested_y_mm" in normalized:
normalized["y_mm"] = float(normalized["requested_y_mm"]) + camera_y_offset
if "requested_x_mm" not in normalized and "x_mm" in normalized:
normalized["requested_x_mm"] = float(normalized["x_mm"]) - camera_x_offset
if "requested_y_mm" not in normalized and "y_mm" in normalized:
normalized["requested_y_mm"] = float(normalized["y_mm"]) - camera_y_offset
normalized["training_tray_calibration_source"] = calibration.get("source")
normalized["training_tray_x_left_mm"] = calibration["x_left_mm"]
normalized["training_tray_x_right_mm"] = calibration["x_right_mm"]
normalized["training_tray_y_top_mm"] = calibration["y_top_mm"]
normalized["training_tray_y_bottom_mm"] = calibration["y_bottom_mm"]
normalized["training_camera_x_offset_mm"] = camera_x_offset
normalized["training_camera_y_offset_mm"] = camera_y_offset
return normalized
def load_manifest(scan_dir: Path, calibration: dict[str, Any]) -> list[dict[str, Any]]:
manifest_path = scan_dir / "manifest.jsonl"
records: list[dict[str, Any]] = []
if not manifest_path.exists():
return records
with manifest_path.open("r", encoding="utf-8") as handle:
for line in handle:
line = line.strip()
if not line:
continue
try:
records.append(normalize_manifest_frame(json.loads(line), calibration))
except json.JSONDecodeError:
continue
return records
def make_dark_mask(gray: np.ndarray, threshold: int) -> np.ndarray:
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
_, mask = cv2.threshold(blurred, threshold, 255, cv2.THRESH_BINARY_INV)
# Fill light writing/reflection gaps inside dark targets, then remove specks.
mask = cv2.morphologyEx(
mask,
cv2.MORPH_CLOSE,
cv2.getStructuringElement(cv2.MORPH_RECT, (CLOSE_KERNEL_SIZE, CLOSE_KERNEL_SIZE)),
)
mask = cv2.morphologyEx(
mask,
cv2.MORPH_OPEN,
cv2.getStructuringElement(cv2.MORPH_RECT, (OPEN_KERNEL_SIZE, OPEN_KERNEL_SIZE)),
)
return mask
def make_pink_mask(image: np.ndarray) -> np.ndarray:
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
hue = hsv[:, :, 0]
saturation = hsv[:, :, 1]
value = hsv[:, :, 2]
blue = image[:, :, 0].astype(np.int16)
green = image[:, :, 1].astype(np.int16)
red = image[:, :, 2].astype(np.int16)
red_dominant_pink = (
(saturation >= PINK_MIN_SATURATION)
& (value >= PINK_MIN_VALUE)
& (hue >= PINK_MIN_HUE)
& (red - np.maximum(green, blue) >= PINK_RED_DOMINANCE)
)
pink_pixels = red_dominant_pink
mask = (pink_pixels.astype(np.uint8)) * 255
mask = cv2.dilate(
mask,
cv2.getStructuringElement(
cv2.MORPH_ELLIPSE,
(PINK_DILATE_KERNEL_SIZE, PINK_DILATE_KERNEL_SIZE),
),
iterations=1,
)
return mask
def make_bug_mask(image: np.ndarray, threshold: int) -> tuple[np.ndarray, np.ndarray]:
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (3, 3), 0)
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
saturation = hsv[:, :, 1]
color_present = float(np.percentile(saturation, 99)) >= COLOR_PRESENT_SATURATION_P99
if color_present:
dark_pixels = (blurred < max(threshold, 165)) & (saturation > 25)
very_dark_pixels = blurred < 100
dark_mask = ((dark_pixels | very_dark_pixels).astype(np.uint8)) * 255
else:
_, dark_mask = cv2.threshold(blurred, threshold, 255, cv2.THRESH_BINARY_INV)
pink_mask = make_pink_mask(image)
mask = cv2.bitwise_and(dark_mask, cv2.bitwise_not(pink_mask))
mask = cv2.morphologyEx(
mask,
cv2.MORPH_OPEN,
cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (OPEN_KERNEL_SIZE, OPEN_KERNEL_SIZE)),
)
mask = cv2.morphologyEx(
mask,
cv2.MORPH_CLOSE,
cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (CLOSE_KERNEL_SIZE, CLOSE_KERNEL_SIZE)),
)
return gray, mask
def make_edge_mask(gray: np.ndarray) -> np.ndarray:
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edges = cv2.Canny(blurred, EDGE_CANNY_LOW, EDGE_CANNY_HIGH)
edges = cv2.dilate(
edges,
cv2.getStructuringElement(cv2.MORPH_RECT, (9, 9)),
iterations=1,
)
edges = cv2.morphologyEx(
edges,
cv2.MORPH_CLOSE,
cv2.getStructuringElement(cv2.MORPH_RECT, (21, 21)),
)
edges = cv2.morphologyEx(
edges,
cv2.MORPH_OPEN,
cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)),
)
return edges
def make_bright_object_mask(gray: np.ndarray) -> np.ndarray:
local_background = cv2.GaussianBlur(gray, (0, 0), 45)
bright_residual = cv2.subtract(gray, local_background)
mask = ((bright_residual > BUG_BRIGHT_RESIDUAL_THRESHOLD) & (gray < 245)).astype(np.uint8) * 255
mask = cv2.morphologyEx(
mask,
cv2.MORPH_OPEN,
cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)),
)
mask = cv2.morphologyEx(
mask,
cv2.MORPH_CLOSE,
cv2.getStructuringElement(cv2.MORPH_RECT, (31, 31)),
)
return mask
def make_body_color_mask(image: np.ndarray) -> np.ndarray:
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
hue = hsv[:, :, 0]
saturation = hsv[:, :, 1]
value = hsv[:, :, 2]
local_background = cv2.GaussianBlur(gray, (0, 0), 45)
darker_than_background = gray < (local_background - 10)
warm_body = ((hue < 35) | (hue > 145)) & (saturation > 15) & (value < 230)
colored_body = (saturation > 22) & (value < 220) & (gray < 205)
mask = ((warm_body | colored_body | darker_than_background) & (gray < 230)).astype(np.uint8) * 255
mask = cv2.bitwise_and(mask, cv2.bitwise_not(make_pink_mask(image)))
mask = cv2.morphologyEx(
mask,
cv2.MORPH_OPEN,
cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)),
)
mask = cv2.morphologyEx(
mask,
cv2.MORPH_CLOSE,
cv2.getStructuringElement(cv2.MORPH_RECT, (19, 19)),
)
return mask
def contour_contrast(gray: np.ndarray, contour: np.ndarray) -> tuple[float, float, float]:
object_mask = np.zeros(gray.shape, dtype=np.uint8)
cv2.drawContours(object_mask, [contour], -1, 255, -1)
dilated_mask = cv2.dilate(
object_mask,
cv2.getStructuringElement(cv2.MORPH_RECT, (25, 25)),
iterations=1,
)
ring_mask = cv2.subtract(dilated_mask, object_mask)
inside_mean = float(cv2.mean(gray, mask=object_mask)[0])
ring_mean = float(cv2.mean(gray, mask=ring_mask)[0])
return inside_mean, ring_mean, ring_mean - inside_mean
def axis_iou(first: dict[str, Any], second: dict[str, Any]) -> float:
ax0 = first["axis_bbox_x_px"]
ay0 = first["axis_bbox_y_px"]
ax1 = ax0 + first["axis_bbox_width_px"]
ay1 = ay0 + first["axis_bbox_height_px"]
bx0 = second["axis_bbox_x_px"]
by0 = second["axis_bbox_y_px"]
bx1 = bx0 + second["axis_bbox_width_px"]
by1 = by0 + second["axis_bbox_height_px"]
ix0 = max(ax0, bx0)
iy0 = max(ay0, by0)
ix1 = min(ax1, bx1)
iy1 = min(ay1, by1)
intersection = max(0, ix1 - ix0) * max(0, iy1 - iy0)
if intersection == 0:
return 0.0
first_area = max(0, ax1 - ax0) * max(0, ay1 - ay0)
second_area = max(0, bx1 - bx0) * max(0, by1 - by0)
union = first_area + second_area - intersection
return intersection / union if union else 0.0
def same_detection(first: dict[str, Any], second: dict[str, Any]) -> bool:
dx = first["centroid_x_px"] - second["centroid_x_px"]
dy = first["centroid_y_px"] - second["centroid_y_px"]
center_distance = (dx * dx + dy * dy) ** 0.5
return center_distance < 90 or axis_iou(first, second) > 0.20
def deduplicate_detections(detections: list[dict[str, Any]]) -> list[dict[str, Any]]:
kept: list[dict[str, Any]] = []
for detection in sorted(detections, key=lambda item: item["score"], reverse=True):
if not any(same_detection(detection, existing) for existing in kept):
kept.append(detection)
kept.sort(key=lambda item: (item["centroid_y_px"], item["centroid_x_px"]))
return kept
def reject_image_edge_detections(
detections: list[dict[str, Any]],
image_shape: tuple[int, int],
margin_px: int = IMAGE_EDGE_REJECT_MARGIN_PX,
) -> list[dict[str, Any]]:
image_height, image_width = image_shape[:2]
kept = []
for detection in detections:
x = detection["axis_bbox_x_px"]
y = detection["axis_bbox_y_px"]
w = detection["axis_bbox_width_px"]
h = detection["axis_bbox_height_px"]
if x <= margin_px or y <= margin_px:
continue
if x + w >= image_width - margin_px or y + h >= image_height - margin_px:
continue
kept.append(detection)
return kept
def detect_rectangles_from_mask(
gray: np.ndarray,
mask: np.ndarray,
*,
method: str,
min_area_px: int,
max_area_fraction: float,
max_rect_area_fraction: float,
max_short_side_fraction: float,
max_long_side_fraction: float,
min_rectangularity: float,
min_aspect_ratio: float,
max_aspect_ratio: float,
max_inside_mean_intensity: float,
min_background_contrast: float,
min_abs_contrast: float = 0,
require_dark: bool = True,
) -> list[dict[str, Any]]:
image_area = gray.shape[0] * gray.shape[1]
reference_side = min(gray.shape[0], gray.shape[1])
max_area = image_area * max_area_fraction
max_rect_area = image_area * max_rect_area_fraction
max_short_side = reference_side * max_short_side_fraction
max_long_side = reference_side * max_long_side_fraction
detections: list[dict[str, Any]] = []
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
area = float(cv2.contourArea(contour))
if area < min_area_px or area > max_area:
continue
rect = cv2.minAreaRect(contour)
(center_x, center_y), (width, height), angle = rect
rect_area = float(width * height)
if rect_area <= 0:
continue
short_side = float(min(width, height))
long_side = float(max(width, height))
if short_side <= 0:
continue
if rect_area > max_rect_area:
continue
if short_side > max_short_side or long_side > max_long_side:
continue
aspect_ratio = long_side / short_side
if aspect_ratio < min_aspect_ratio or aspect_ratio > max_aspect_ratio:
continue
rectangularity = area / rect_area
if rectangularity < min_rectangularity:
continue
mean_intensity, background_mean, contrast = contour_contrast(gray, contour)
abs_contrast = abs(contrast)
if require_dark and mean_intensity > max_inside_mean_intensity:
continue
if require_dark and contrast < min_background_contrast:
continue
if abs_contrast < min_abs_contrast:
continue
box = cv2.boxPoints(rect)
box = np.intp(box)
x, y, w, h = cv2.boundingRect(box)
score = max(contrast, abs_contrast) * rectangularity * min(aspect_ratio, 3.0)
detections.append(
{
"detection_method": method,
"centroid_x_px": float(center_x),
"centroid_y_px": float(center_y),
"axis_bbox_x_px": int(x),
"axis_bbox_y_px": int(y),
"axis_bbox_width_px": int(w),
"axis_bbox_height_px": int(h),
"rotated_box_px": box.astype(float).tolist(),
"area_px": area,
"rect_area_px": rect_area,
"rect_width_px": float(width),
"rect_height_px": float(height),
"rect_short_side_px": short_side,
"rect_long_side_px": long_side,
"rectangularity": float(rectangularity),
"aspect_ratio": float(aspect_ratio),
"mean_intensity": mean_intensity,
"background_mean_intensity": background_mean,
"background_contrast": contrast,
"absolute_background_contrast": abs_contrast,
"angle_degrees": float(angle),
"score": float(score),
}
)
detections.sort(key=lambda item: (item["centroid_y_px"], item["centroid_x_px"]))
return detections
def detect_rectangles(
gray: np.ndarray,
dark_mask: np.ndarray,
edge_mask: np.ndarray,
*,
min_area_px: int,
max_area_fraction: float,
max_rect_area_fraction: float,
max_short_side_fraction: float,
max_long_side_fraction: float,
min_rectangularity: float,
min_aspect_ratio: float,
max_aspect_ratio: float,
max_inside_mean_intensity: float,
min_background_contrast: float,
) -> list[dict[str, Any]]:
dark_detections = detect_rectangles_from_mask(
gray,
dark_mask,
method="dark_mask",
min_area_px=min_area_px,
max_area_fraction=max_area_fraction,
max_rect_area_fraction=max_rect_area_fraction,
max_short_side_fraction=max_short_side_fraction,
max_long_side_fraction=max_long_side_fraction,
min_rectangularity=min_rectangularity,
min_aspect_ratio=min_aspect_ratio,
max_aspect_ratio=max_aspect_ratio,
max_inside_mean_intensity=max_inside_mean_intensity,
min_background_contrast=min_background_contrast,
)
edge_detections = detect_rectangles_from_mask(
gray,
edge_mask,
method="edge_mask",
min_area_px=EDGE_MIN_AREA_PX,
max_area_fraction=0.08,
max_rect_area_fraction=0.10,
max_short_side_fraction=0.30,
max_long_side_fraction=0.50,
min_rectangularity=EDGE_MIN_RECTANGULARITY,
min_aspect_ratio=EDGE_MIN_ASPECT_RATIO,
max_aspect_ratio=EDGE_MAX_ASPECT_RATIO,
max_inside_mean_intensity=255,
min_background_contrast=0,
min_abs_contrast=EDGE_MIN_ABS_CONTRAST,
require_dark=False,
)
return deduplicate_detections(dark_detections + edge_detections)
def detect_bugs(
image: np.ndarray,
gray: np.ndarray,
mask: np.ndarray,
*,
min_area_px: int,
max_area_fraction: float,
max_short_side_fraction: float,
max_long_side_fraction: float,
min_rectangularity: float,
min_aspect_ratio: float,
max_aspect_ratio: float,
max_inside_mean_intensity: float,
min_background_contrast: float,
) -> list[dict[str, Any]]:
image_area = gray.shape[0] * gray.shape[1]
reference_side = min(gray.shape[0], gray.shape[1])
saturation_p99 = float(np.percentile(cv2.cvtColor(image, cv2.COLOR_BGR2HSV)[:, :, 1], 99))
color_present = saturation_p99 >= COLOR_PRESENT_SATURATION_P99
effective_min_area_px = max(min_area_px, COLOR_MIN_AREA_PX) if color_present else max(
min_area_px,
GRAYSCALE_MIN_AREA_PX,
)
effective_min_aspect_ratio = min_aspect_ratio if color_present else max(
min_aspect_ratio,
GRAYSCALE_MIN_AXIS_ASPECT_RATIO,
)
effective_max_aspect_ratio = (
min(max_aspect_ratio, COLOR_MAX_AXIS_ASPECT_RATIO)
if color_present
else max_aspect_ratio
)
effective_min_rectangularity = max(
min_rectangularity,
COLOR_MIN_RECTANGULARITY if color_present else GRAYSCALE_MIN_RECTANGULARITY,
)
effective_max_inside_mean = (
min(max_inside_mean_intensity, COLOR_MAX_INSIDE_MEAN_INTENSITY)
if color_present
else min(max_inside_mean_intensity, GRAYSCALE_MAX_INSIDE_MEAN_INTENSITY)
)
effective_min_background_contrast = (
min(min_background_contrast, COLOR_MIN_BACKGROUND_CONTRAST)
if color_present
else min_background_contrast
)
effective_max_short_side_fraction = (
max(max_short_side_fraction, COLOR_MAX_SHORT_SIDE_FRACTION)
if color_present
else max_short_side_fraction
)
effective_max_long_side_fraction = (
max(max_long_side_fraction, COLOR_MAX_LONG_SIDE_FRACTION)
if color_present
else max_long_side_fraction
)
max_area = image_area * max_area_fraction
max_short_side = reference_side * effective_max_short_side_fraction
max_long_side = reference_side * effective_max_long_side_fraction
detections: list[dict[str, Any]] = []
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
area = float(cv2.contourArea(contour))
if area < effective_min_area_px or area > max_area:
continue
x, y, w, h = cv2.boundingRect(contour)
if (
x <= IMAGE_EDGE_REJECT_MARGIN_PX
or y <= IMAGE_EDGE_REJECT_MARGIN_PX
or x + w >= gray.shape[1] - IMAGE_EDGE_REJECT_MARGIN_PX
or y + h >= gray.shape[0] - IMAGE_EDGE_REJECT_MARGIN_PX
):
continue
short_side = float(min(w, h))
long_side = float(max(w, h))
if short_side <= 0:
continue
axis_aspect_ratio = long_side / short_side
if axis_aspect_ratio < effective_min_aspect_ratio or axis_aspect_ratio > effective_max_aspect_ratio:
continue
if short_side > max_short_side or long_side > max_long_side:
continue
bbox_area = float(w * h)
fill_ratio = area / bbox_area if bbox_area else 0.0
if fill_ratio < BUG_MIN_FILL_RATIO:
continue
moments = cv2.moments(contour)
if abs(moments["m00"]) < 0.000001:
continue
center_x = moments["m10"] / moments["m00"]
center_y = moments["m01"] / moments["m00"]
mean_intensity, background_mean, contrast = contour_contrast(gray, contour)
if mean_intensity > effective_max_inside_mean:
continue
if contrast < effective_min_background_contrast:
continue
if (
color_present
and contrast < COLOR_MIN_USEFUL_CONTRAST
and mean_intensity > COLOR_MAX_LOW_CONTRAST_MEAN_INTENSITY
):
continue
rect = cv2.minAreaRect(contour)
(_, _), (rect_width, rect_height), angle = rect
rect_area = float(rect_width * rect_height)
if rect_area <= 0:
continue
rect_short_side = float(min(rect_width, rect_height))
rect_long_side = float(max(rect_width, rect_height))
aspect_ratio = rect_long_side / rect_short_side if rect_short_side else 0.0
rectangularity = area / rect_area
if rectangularity < effective_min_rectangularity:
continue
box = cv2.boxPoints(rect)
box = np.intp(box)
score = contrast * area * min(fill_ratio * 4.0, 1.0)
detections.append(
{
"detection_method": "bug_dark_color_mask",
"centroid_x_px": float(center_x),
"centroid_y_px": float(center_y),
"axis_bbox_x_px": int(x),
"axis_bbox_y_px": int(y),
"axis_bbox_width_px": int(w),
"axis_bbox_height_px": int(h),
"rotated_box_px": box.astype(float).tolist(),
"area_px": area,
"rect_area_px": rect_area,
"rect_width_px": float(rect_width),
"rect_height_px": float(rect_height),
"rect_short_side_px": rect_short_side,
"rect_long_side_px": rect_long_side,
"rectangularity": float(rectangularity),
"aspect_ratio": float(aspect_ratio),
"mean_intensity": mean_intensity,
"background_mean_intensity": background_mean,
"background_contrast": contrast,
"absolute_background_contrast": abs(contrast),
"angle_degrees": float(angle),
"score": float(score),
}
)
outline_detections = detect_rectangles_from_mask(
gray,
make_edge_mask(gray),
method="bug_outline_mask",
min_area_px=BUG_OUTLINE_MIN_AREA_PX,
max_area_fraction=max_area_fraction,
max_rect_area_fraction=max_area_fraction,
max_short_side_fraction=effective_max_short_side_fraction,
max_long_side_fraction=effective_max_long_side_fraction,
min_rectangularity=max(0.40, min_rectangularity),
min_aspect_ratio=1.15,
max_aspect_ratio=min(max_aspect_ratio, 5.0),
max_inside_mean_intensity=BUG_OUTLINE_MAX_INSIDE_MEAN_INTENSITY,
min_background_contrast=0,
min_abs_contrast=BUG_OUTLINE_MIN_ABS_CONTRAST,
require_dark=True,
)
outline_detections = reject_image_edge_detections(outline_detections, gray.shape)
bright_detections = detect_rectangles_from_mask(
gray,
make_bright_object_mask(gray),
method="bug_bright_mask",
min_area_px=BUG_BRIGHT_MIN_AREA_PX,
max_area_fraction=max_area_fraction,
max_rect_area_fraction=max_area_fraction,
max_short_side_fraction=effective_max_short_side_fraction,
max_long_side_fraction=effective_max_long_side_fraction,
min_rectangularity=max(0.35, min_rectangularity),
min_aspect_ratio=1.15,
max_aspect_ratio=max(max_aspect_ratio, 6.0),
max_inside_mean_intensity=255,
min_background_contrast=0,
min_abs_contrast=BUG_BRIGHT_MIN_ABS_CONTRAST,
require_dark=False,
)
bright_detections = reject_image_edge_detections(bright_detections, gray.shape)
body_color_detections = detect_rectangles_from_mask(
gray,
make_body_color_mask(image),
method="bug_body_color_mask",
min_area_px=BUG_BODY_COLOR_MIN_AREA_PX,
max_area_fraction=max(max_area_fraction, 0.055),
max_rect_area_fraction=max(max_area_fraction, 0.080),
max_short_side_fraction=max(effective_max_short_side_fraction, 0.50),
max_long_side_fraction=max(effective_max_long_side_fraction, 0.65),
min_rectangularity=0.10,
min_aspect_ratio=0.65,
max_aspect_ratio=max(max_aspect_ratio, 6.0),
max_inside_mean_intensity=220,
min_background_contrast=-25,
min_abs_contrast=BUG_BODY_COLOR_MIN_ABS_CONTRAST,
require_dark=False,
)
body_color_detections = reject_image_edge_detections(body_color_detections, gray.shape)
return deduplicate_detections(detections + outline_detections + bright_detections + body_color_detections)
def image_point_to_machine_coordinates(
frame: dict[str, Any],
centroid_x_px: float,
centroid_y_px: float,
frame_center_x: float,
frame_center_y: float,
) -> tuple[float, float]:
image_width = frame["image_width_px"]
image_height = frame["image_height_px"]
upp_x = frame["units_per_pixel_x_mm"]
upp_y = frame["units_per_pixel_y_mm"]
dx_mm = (centroid_x_px - (image_width / 2.0)) * upp_x
dy_mm = (centroid_y_px - (image_height / 2.0)) * upp_y
return frame_center_x + dx_mm, frame_center_y - dy_mm
def object_machine_coordinates(frame: dict[str, Any], centroid_x_px: float, centroid_y_px: float) -> tuple[float, float]:
return image_point_to_machine_coordinates(
frame,
centroid_x_px,
centroid_y_px,
frame["x_mm"],
frame["y_mm"],
)
def body_biased_pick_point(image: np.ndarray, detection: dict[str, Any]) -> tuple[float, float]:
"""Choose a pick point near the insect body, not the wing-heavy silhouette center."""
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
saturation = hsv[:, :, 1].astype(np.float32)
value = hsv[:, :, 2]
polygon = np.array(detection["rotated_box_px"], dtype=np.int32)
detection_mask = np.zeros(gray.shape, dtype=np.uint8)
cv2.fillPoly(detection_mask, [polygon], 255)
body_pixels = (
(detection_mask > 0)
& (
(gray < 150)
| ((saturation > 45) & (value < 230))
)
& ~((gray > 175) & (saturation < 35))
)
if int(np.count_nonzero(body_pixels)) < 20:
return float(detection["centroid_x_px"]), float(detection["centroid_y_px"])
weights = (
np.maximum(0, 190 - gray.astype(np.float32))
+ (saturation * 0.8)
)
weights = np.where(body_pixels, weights, 0.0)
total_weight = float(weights.sum())
if total_weight <= 0:
return float(detection["centroid_x_px"]), float(detection["centroid_y_px"])
core_pixels = (
(detection_mask > 0)
& (
(gray < 135)
| ((saturation > 60) & (value < 215))
)
& ~((gray > 165) & (saturation < 45))
)
core_mask = core_pixels.astype(np.uint8)
core_mask = cv2.morphologyEx(
core_mask,
cv2.MORPH_OPEN,
cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)),
)
body_mask = core_mask if int(np.count_nonzero(core_mask)) >= 20 else body_pixels.astype(np.uint8)
component_count, labels, stats, _ = cv2.connectedComponentsWithStats(body_mask, 8)
best_label = 0
best_score = 0.0
detection_x = float(detection["centroid_x_px"])
detection_y = float(detection["centroid_y_px"])
for label in range(1, component_count):
area = float(stats[label, cv2.CC_STAT_AREA])
if area < 20.0:
continue
component_pixels = labels == label
component_weight = float(weights[component_pixels].sum())
if component_weight <= 0:
continue
yy_component, xx_component = np.nonzero(component_pixels)
component_x = float((xx_component * weights[component_pixels]).sum() / component_weight)
component_y = float((yy_component * weights[component_pixels]).sum() / component_weight)
distance_px = ((component_x - detection_x) ** 2 + (component_y - detection_y) ** 2) ** 0.5
score = component_weight / (1.0 + max(0.0, distance_px - 180.0) * 0.01)
if score > best_score:
best_score = score
best_label = label
if best_label:
component_mask = (labels == best_label).astype(np.uint8)
distance_to_edge = cv2.distanceTransform(component_mask, cv2.DIST_L2, 5)
body_strength = distance_to_edge * 8.0 + (weights * component_mask)
_, _, _, max_location = cv2.minMaxLoc(body_strength.astype(np.float32))
pick_x = float(max_location[0])
pick_y = float(max_location[1])
return pick_x, pick_y
yy, xx = np.indices(gray.shape)
pick_x = float((xx * weights).sum() / total_weight)
pick_y = float((yy * weights).sum() / total_weight)
return pick_x, pick_y
def crop_detection(image: np.ndarray, detection: dict[str, Any], padding: int) -> np.ndarray:
x = detection["axis_bbox_x_px"]
y = detection["axis_bbox_y_px"]
w = detection["axis_bbox_width_px"]
h = detection["axis_bbox_height_px"]
x0 = max(0, x - padding)
y0 = max(0, y - padding)
x1 = min(image.shape[1], x + w + padding)
y1 = min(image.shape[0], y + h + padding)
return image[y0:y1, x0:x1]
def detection_quality(record: dict[str, Any]) -> float:
edge_penalty = 0.0
image_width = float(record.get("image_width_px") or 0)
image_height = float(record.get("image_height_px") or 0)
bbox_x = float(record.get("bbox_x_px") or 0)
bbox_y = float(record.get("bbox_y_px") or 0)
bbox_width = float(record.get("bbox_width_px") or 0)
bbox_height = float(record.get("bbox_height_px") or 0)
if image_width > 0 and image_height > 0 and bbox_width > 0 and bbox_height > 0:
edge_clearance = min(
bbox_x,
bbox_y,
image_width - (bbox_x + bbox_width),
image_height - (bbox_y + bbox_height),
)
edge_penalty = max(0.0, 120.0 - edge_clearance) * 20000.0
return float(record.get("score") or 0.0) + (float(record.get("bbox_area_px") or 0.0) * 80.0) - edge_penalty
def assign_duplicate_metadata(records: list[dict[str, Any]], minimum_distance_mm: float) -> list[dict[str, Any]]:
unique: list[dict[str, Any]] = []
duplicate_pairs: list[tuple[dict[str, Any], dict[str, Any]]] = []
for candidate_index, record in enumerate(records):
record["candidate_index"] = candidate_index
record["is_duplicate"] = False
record["duplicate_of_object_index"] = None
record["duplicate_distance_mm"] = None
for record in sorted(records, key=detection_quality, reverse=True):
duplicate_of: dict[str, Any] | None = None
duplicate_distance: float | None = None
for kept in unique:
dx = float(record["pick_x_mm"]) - float(kept["pick_x_mm"])
dy = float(record["pick_y_mm"]) - float(kept["pick_y_mm"])
distance = (dx * dx + dy * dy) ** 0.5
if distance < minimum_distance_mm:
duplicate_of = kept
duplicate_distance = distance
break
if duplicate_of is None:
unique.append(record)
else:
record["is_duplicate"] = True
record["duplicate_distance_mm"] = duplicate_distance
duplicate_pairs.append((record, duplicate_of))
unique.sort(key=lambda item: (int(item["frame_index"]), int(item["object_index"])))
for object_index, record in enumerate(unique):
record["object_index"] = object_index