forked from yoav-ayalon/course-IPCV
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2112 lines (1675 loc) · 75.9 KB
/
Copy pathmain.py
File metadata and controls
2112 lines (1675 loc) · 75.9 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
import numpy as np
import matplotlib.pyplot as plt
import cv2
from skimage import filters, exposure
from skimage.io import imsave
import os
from typing import List, Union
from pathlib import Path
import scipy.ndimage as ndi
script_dir = Path(__file__).resolve().parent
images_dir = script_dir/"IMG"
video_dir = script_dir/"VID"
model_dir = script_dir/"model"
rect_start = None
rect_end = None
drawing = False
###----------------------------------- Initialization ----------------------------------------
def load_image(name: str):
path = images_dir / name
if not path.exists():
raise FileNotFoundError(f"Image not found: {path}")
# Read raw bytes with numpy (handles Unicode paths fine)
data = np.fromfile(str(path), dtype=np.uint8)
if data.size == 0:
raise IOError(f"Failed to read any data from: {path}")
# Decode the image from memory
bgr = cv2.imdecode(data, cv2.IMREAD_COLOR)
if bgr is None:
raise IOError(f"cv2.imdecode failed for: {path}")
gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)
rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
return bgr, gray, rgb
def load_video(name: str):
"""
Load a video file and return a VideoCapture object with metadata.
Args:
name: Video filename (e.g., "my_video.mp4")
Returns:
cap: cv2.VideoCapture object
metadata: dict with 'fps', 'width', 'height', 'frame_count', 'duration'
"""
path = video_dir / name
if not path.exists():
raise FileNotFoundError(f"Video not found: {path}")
# Open video file
cap = cv2.VideoCapture(str(path))
if not cap.isOpened():
raise IOError(f"Failed to open video: {path}")
# Extract metadata
fps = cap.get(cv2.CAP_PROP_FPS)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
duration = frame_count / fps if fps > 0 else 0
metadata = {
'fps': fps,
'width': width,
'height': height,
'frame_count': frame_count,
'duration': duration
}
print(f"Video loaded: {name}")
print(f" Resolution: {width}x{height}")
print(f" FPS: {fps:.2f}")
print(f" Frames: {frame_count}")
print(f" Duration: {duration:.2f} seconds")
return cap, metadata
def read_video_frame(cap):
"""
Read next frame from video.
Args:
cap: cv2.VideoCapture object
Returns:
success: Boolean indicating if frame was read successfully
bgr: Frame in BGR format (or None if failed)
gray: Frame in grayscale (or None if failed)
rgb: Frame in RGB format (or None if failed)
"""
ret, bgr = cap.read()
if not ret or bgr is None:
return False, None, None, None
gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)
rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
return True, bgr, gray, rgb
def select_roi_on_rgb(rgb, window_width=1000, window_height=600):
"""
Allow user to select a rectangular ROI on the RGB image using mouse.
The window size is constant, and the image is scaled to fit entirely within it.
Returns (rect_coords, roi_rgb) where rect_coords = (x1, y1, x2, y2).
If no ROI selected, returns (None, None).
"""
global rect_start, rect_end, drawing
rect_start = None
rect_end = None
drawing = False
win_name = "Select ROI (drag with mouse, ENTER/ESC to finish)"
h, w = rgb.shape[:2]
# Always scale to fit the window, whether image is small or large
scale = min(window_width / w, window_height / h)
disp_w, disp_h = int(w * scale), int(h * scale)
rgb_disp = cv2.resize(rgb, (disp_w, disp_h), interpolation=cv2.INTER_AREA if scale < 1 else cv2.INTER_LINEAR)
def mouse_callback(event, x, y, flags, param):
global rect_start, rect_end, drawing
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
rect_start = (x, y)
rect_end = (x, y)
elif event == cv2.EVENT_MOUSEMOVE and drawing:
rect_end = (x, y)
elif event == cv2.EVENT_LBUTTONUP:
drawing = False
rect_end = (x, y)
cv2.namedWindow(win_name)
cv2.setMouseCallback(win_name, mouse_callback)
while True:
# Display a copy of the image, with a rectangle if present
frame = rgb_disp.copy()
if rect_start and rect_end:
cv2.rectangle(frame, rect_start, rect_end, (0, 255, 0), 2)
# OpenCV works in BGR, so convert only for display purposes
frame_bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
cv2.imshow(win_name, frame_bgr)
key = cv2.waitKey(1) & 0xFF
if key in (13, 27): # ENTER or ESC to finish
break
cv2.destroyWindow(win_name)
if not (rect_start and rect_end):
return None, None
x1, y1 = rect_start
x2, y2 = rect_end
x1, x2 = sorted([x1, x2])
y1, y2 = sorted([y1, y2])
orig_x1 = int(x1 / scale)
orig_y1 = int(y1 / scale)
orig_x2 = int(x2 / scale)
orig_y2 = int(y2 / scale)
roi_rgb = rgb[orig_y1:orig_y2, orig_x1:orig_x2]
return (orig_x1, orig_y1, orig_x2, orig_y2), roi_rgb
def select_mode():
"""
Prompt user to select between image and video processing modes.
Returns:
mode: 'image' or 'video'
"""
print("\n" + "="*60)
print(" IMAGE/VIDEO ANONYMIZATION TOOL")
print("="*60)
print("\nPlease select a processing mode:\n")
print(" 1. Image mode - Process a single image")
print(" 2. Video mode - Process a video with object tracking")
print()
while True:
choice = input("Enter your choice (1 or 2): ").strip()
if choice == '1':
return 'image'
elif choice == '2':
return 'video'
else:
print("Invalid choice. Please enter 1 or 2.")
def select_tracker():
"""
Prompt user to select tracking method for video processing.
Returns:
tracker: Instantiated MaskTracker (FlowWarpTracker or KLTTracker)
"""
print("\n" + "="*60)
print(" SELECT TRACKING METHOD")
print("="*60)
print("\nAvailable tracking methods:\n")
print(" 1. Dense Optical Flow - Pixel-wise warping (Farneback algorithm)")
print(" 2. KLT Feature Tracking - Global transform (feature points)")
while True:
choice = input("Enter your choice (1 or 2): ").strip()
if choice == '1':
print("\nUsing FlowWarpTracker (Dense Optical Flow)")
return FlowWarpTracker(
roi_margin=30,
min_mask_area=300,
morph_kernel_size=5,
morph_close_iterations=2,
morph_open_iterations=1
)
elif choice == '2':
print("\nUsing KLTTracker (Feature Point Tracking)")
return KLTTracker(
max_points=150,
quality_level=0.01,
min_distance=10,
reinit_threshold=0.3,
refine_kernel_size=5,
refine_iterations=1
)
else:
print("Invalid choice. Please enter 1 or 2.")
def select_segmentation_method():
"""
Prompt user to select initial segmentation method for first frame.
Returns:
method: 'sam' or 'corners'
"""
print("\n" + "="*60)
print(" SELECT SEGMENTATION METHOD")
print("="*60)
print("\nChoose initial mask generation method:\n")
print(" 1. SAM (Segment Anything Model)")
print(" 2. Corner Detection (Shi-Tomasi) + Convex Hull")
while True:
choice = input("Enter your choice (1 or 2): ").strip()
if choice == '1':
return 'sam'
elif choice == '2':
return 'corners'
else:
print("Invalid choice. Please enter 1 or 2.")
###----------------------------------- Helper funcations ----------------------------------------
def show_image(img_or_list: Union[np.ndarray, List[np.ndarray]],
row_plot: int = 1,
titles: List[str] = None):
"""
Display one or multiple images in a grid using Matplotlib.
- img_or_list: single image or list of images (H×W or H×W×3)
- row_plot: number of rows in the grid
- titles: optional list of titles, same length as images
"""
imgs = img_or_list if isinstance(img_or_list, list) else [img_or_list]
n = len(imgs)
rows = row_plot
cols = int(np.ceil(n / rows))
fig, axes = plt.subplots(rows, cols, figsize=(4 * cols, 4 * rows))
axes = np.array(axes).reshape(-1) if isinstance(axes, np.ndarray) else np.array([axes])
for i, im in enumerate(imgs):
if im.ndim == 2:
axes[i].imshow(im, cmap='gray')
else:
axes[i].imshow(im)
axes[i].axis('off')
if titles is not None and i < len(titles):
axes[i].set_title(titles[i])
for j in range(i + 1, len(axes)):
axes[j].axis('off')
plt.tight_layout()
plt.show()
def _imshow_with_histogram(image, **kwargs):
"""
Show image and its histogram side-by-side.
"""
def _iter_channels(color_image):
for channel in np.rollaxis(color_image, -1):
yield channel
def _hist(ax, image, alpha=0.3, **kwargs):
hist, bin_centers = exposure.histogram(image)
ax.fill_between(bin_centers, hist, alpha=alpha, **kwargs)
ax.set_xlabel('intensity')
ax.set_ylabel('# pixels')
def _plot_histogram(image, ax=None, **kwargs):
ax = ax if ax is not None else plt.gca()
if image.ndim == 2:
_hist(ax, image, color='black', **kwargs)
elif image.ndim == 3:
for channel, channel_color in zip(_iter_channels(image), 'rgb'):
_hist(ax, channel, color=channel_color, **kwargs)
def _match_axes_height(ax_src, ax_dst):
plt.draw()
dst = ax_dst.get_position()
src = ax_src.get_position()
ax_dst.set_position([dst.xmin, src.ymin, dst.width, src.height])
width, height = plt.rcParams['figure.figsize']
fig, (ax_image, ax_hist) = plt.subplots(ncols=2, figsize=(2 * width, height))
kwargs.setdefault('cmap', plt.cm.gray)
ax_image.imshow(image, **kwargs)
_plot_histogram(image, ax=ax_hist)
ax_image.set_axis_off()
_match_axes_height(ax_image, ax_hist)
return ax_image, ax_hist
###----------------------------------- first image processing functions -------------------------------
def binary_mask(roi_gray):
t_otsu = filters.threshold_otsu(roi_gray)
roi_binary_mask = (roi_gray > t_otsu).astype(np.uint8) * 255
#show_image([roi_gray, roi_binary_mask], row_plot=1)
# roi_binary_mask: 0/255 uint8 mask from above
return cv2.bitwise_and(roi_gray, roi_gray, mask=roi_binary_mask)
def diliation(roi_gray):
k7 = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7))
dilated = cv2.dilate(roi_gray, k7, iterations=1)
show_image(
[roi_gray, dilated], row_plot=1,
titles=["Binary", "Dilate (3×3) – grows strokes, fills small gaps, makes much noise in the backround"])
return dilated
def Morphological_gradient(roi_gray):
# Choose a structuring element
k = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
# Dilate the binary mask
dilated = cv2.dilate(roi_gray, k)
# Subtract the original binary image from the dilated version
# → the difference is only the NEW outer pixels that appeared
outer = cv2.absdiff(dilated, roi_gray)
# Visualize
show_image([roi_gray, outer],
titles=["Binary image", "Outer contour (from dilation)"])
return outer
def clahe(roi_gray):
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
he_clahe = clahe.apply(roi_gray)
ax_img, ax_hist = _imshow_with_histogram(he_clahe)
show_image([roi_gray, he_clahe], row_plot=1, titles=["Original", "CLAHE (local equalization)"],)
return he_clahe
def unsharp_masking(roi_gray):
blur = ndi.gaussian_filter(roi_gray, sigma=1.0)
# High-frequency component (edges/details)
high_freq = roi_gray - blur
# Sharpen: original + α * high_freq
alpha = 0.5
sharp = np.clip(roi_gray + alpha * high_freq, 0, 1)
show_image([roi_gray, blur, high_freq, sharp], row_plot=1, titles=["Original", "Blurred", "High freq (a - blur)", "Sharpened (unsharp mask)"])
return high_freq
###----------------------------------- second image processing functions ------------------------------
def custom_kernel(roi_gray):
kernel_sharp = np.array([[-1,-1,-1],
[-1, 9,-1],
[-1,-1,-1]], np.float32)
sharp = cv2.filter2D(roi_gray, -1, kernel_sharp)
show_image([sharp], titles=["sharp"], row_plot=1)
return sharp
def sobel(roi_gray):
# Sobel gradients (derivatives)
sx = cv2.Sobel(roi_gray, cv2.CV_32F, 1, 0, ksize=3)
sy = cv2.Sobel(roi_gray, cv2.CV_32F, 0, 1, ksize=3)
sobel_mag = cv2.magnitude(sx, sy)
show_image([sx, sy, sobel_mag], row_plot=1,
titles='Sobel X | Sobel Y | Magnitude')
return sobel_mag
def laplacian(roi_gray):
# Laplacian (second derivative)
lap = cv2.Laplacian(roi_gray, cv2.CV_32F, ksize=3)
show_image([lap], row_plot=1, titles='Laplacian')
return lap
def canny(roi_gray):
# Canny (works on 8-bit)
g8 = (roi_gray*255).astype(np.uint8)
edges = cv2.Canny(g8, threshold1=30, threshold2=90)
show_image([edges], row_plot=1, titles='Canny')
return edges
###----------------------------------- segmentation functions -------------------------------
def _overlay_mask(rgb: np.ndarray, mask: np.ndarray, alpha: float = 0.5) -> np.ndarray:
"""Overlay a boolean mask on RGB (mask=True highlighted)."""
out = rgb.copy()
if mask.dtype != bool:
mask = mask.astype(bool)
# highlight mask region in red-ish overlay (no fixed colormap assumptions)
highlight = np.zeros_like(out)
highlight[..., 0] = 255 # R channel
out[mask] = (alpha * highlight[mask] + (1 - alpha) * out[mask]).astype(np.uint8)
return out
def grabcut_segmentation(roi_rgb, iterations=5, show_steps=True):
"""
GrabCut segmentation: Estimates foreground within ROI image.
Args:
roi_rgb: ROI RGB image (extracted region)
iterations: Number of GrabCut iterations (default=5)
show_steps: Whether to show intermediate visualization (default=True)
Returns:
mask: Binary mask (0/255) of the segmented object within ROI
final_vis: Visualization with mask overlay
"""
h, w = roi_rgb.shape[:2]
# Use entire ROI as bounding box with small margin
margin = 5
rect_grabcut = (margin, margin, w - 2*margin, h - 2*margin) # (x, y, w, h) format
# Initialize mask and models for GrabCut
mask_grabcut = np.zeros((h, w), dtype=np.uint8)
bgd_model = np.zeros((1, 65), dtype=np.float64)
fgd_model = np.zeros((1, 65), dtype=np.float64)
# Run GrabCut
cv2.grabCut(roi_rgb, mask_grabcut, rect_grabcut, bgd_model, fgd_model,
iterations, cv2.GC_INIT_WITH_RECT)
# Create binary mask (foreground = 1 or 3, background = 0 or 2)
mask_fg = np.where((mask_grabcut == cv2.GC_FGD) | (mask_grabcut == cv2.GC_PR_FGD), 255, 0).astype(np.uint8)
# Keep only largest connected component
num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(mask_fg, connectivity=8)
if num_labels > 1: # 0 is background
# Find largest component (excluding background)
largest_component = 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA])
mask_largest = (labels == largest_component).astype(np.uint8) * 255
else:
mask_largest = mask_fg
# Morphological cleanup (closing then opening)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
mask_cleaned = cv2.morphologyEx(mask_largest, cv2.MORPH_CLOSE, kernel, iterations=2)
mask_cleaned = cv2.morphologyEx(mask_cleaned, cv2.MORPH_OPEN, kernel, iterations=1)
# Visualization
vis_grabcut = _overlay_mask(roi_rgb, mask_fg.astype(bool), alpha=0.4)
vis_largest = _overlay_mask(roi_rgb, mask_largest.astype(bool), alpha=0.4)
vis_final = _overlay_mask(roi_rgb, mask_cleaned.astype(bool), alpha=0.4)
if show_steps:
show_image(
[roi_rgb, vis_grabcut, vis_largest, vis_final],
row_plot=2,
titles=[
"Input ROI",
"GrabCut raw output",
"Largest component only",
"After morphological cleanup"
]
)
print(f"GrabCut: Found {num_labels - 1} components, kept largest")
return mask_cleaned, vis_final
def sam_box_prompt_segmentation(roi_rgb, show_steps=True):
"""
SAM with box prompt: Use entire ROI as box prompt, select best mask automatically.
Args:
roi_rgb: ROI RGB image (extracted region)
show_steps: Whether to show intermediate visualization (default=True)
Returns:
mask: Binary mask (0/255) of the selected object within ROI
final_vis: Visualization with mask overlay
"""
try:
import torch
from segment_anything import sam_model_registry, SamPredictor
except ImportError as e:
print(f"Error: {e}")
print("Install with: pip install torch torchvision segment-anything")
return None, None
# Path to SAM checkpoint
SAM_CKPT = model_dir / "checkpoints" / "sam_vit_b_01ec64.pth"
if not SAM_CKPT.exists():
print(f"Checkpoint not found: {SAM_CKPT}")
print("\nDownload from: https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth")
SAM_CKPT.parent.mkdir(parents=True, exist_ok=True)
return None, None
device = "cuda" if torch.cuda.is_available() else "cpu"
sam = sam_model_registry["vit_b"](checkpoint=str(SAM_CKPT))
sam.to(device=device)
predictor = SamPredictor(sam)
# Convert to RGB uint8 if needed
if roi_rgb.dtype != np.uint8:
roi_rgb_uint8 = (roi_rgb * 255).astype(np.uint8)
else:
roi_rgb_uint8 = roi_rgb
predictor.set_image(roi_rgb_uint8)
# Create box prompt for entire ROI with small margin
h, w = roi_rgb.shape[:2]
margin = 5
box_prompt = np.array([margin, margin, w - margin, h - margin])
# Generate masks with box prompt
masks, scores, logits = predictor.predict(
box=box_prompt,
multimask_output=True # Get 3 mask candidates
)
print(f"SAM box prompt: Generated {len(masks)} candidate masks")
print(f"Scores: {scores}")
# Score each mask based on:
# 1. Area in ROI
# 2. Centroid distance from ROI center
# 3. Penalty for touching ROI borders
h, w = roi_rgb.shape[:2]
roi_center_x, roi_center_y = w / 2, h / 2
roi_area = h * w
best_idx = -1
best_score = -np.inf
mask_scores = []
for i, mask in enumerate(masks):
# Area score (normalized)
area_in_roi = np.sum(mask)
area_score = area_in_roi / roi_area
# Centroid score
if np.sum(mask) > 0:
y_coords, x_coords = np.where(mask)
centroid_x = np.mean(x_coords)
centroid_y = np.mean(y_coords)
dist_to_center = np.sqrt((centroid_x - roi_center_x)**2 + (centroid_y - roi_center_y)**2)
max_dist = np.sqrt(w**2 + h**2) / 2
centroid_score = 1 - (dist_to_center / max_dist)
else:
centroid_score = 0
# Border penalty (if mask touches ROI edges)
border_penalty = 0
if np.any(mask[0, :]) or np.any(mask[-1, :]) or \
np.any(mask[:, 0]) or np.any(mask[:, -1]):
border_penalty = 0.2
# Combined score
combined = scores[i] * 0.4 + area_score * 0.3 + centroid_score * 0.3 - border_penalty
mask_scores.append(combined)
if combined > best_score:
best_score = combined
best_idx = i
print(f"Combined scores: {mask_scores}")
print(f"Selected mask {best_idx} with score {best_score:.3f}")
# Get best mask
best_mask = masks[best_idx].astype(np.uint8) * 255
# Keep only largest connected component
num_labels, labels, stats, _ = cv2.connectedComponentsWithStats(best_mask, connectivity=8)
if num_labels > 1:
largest_component = 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA])
mask_largest = (labels == largest_component).astype(np.uint8) * 255
else:
mask_largest = best_mask
# Light morphological smoothing
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
mask_final = cv2.morphologyEx(mask_largest, cv2.MORPH_CLOSE, kernel, iterations=1)
# Visualization
if show_steps:
vis_candidates = []
for i, mask in enumerate(masks):
vis = _overlay_mask(roi_rgb_uint8, mask.astype(bool), alpha=0.4)
# cv2.putText(vis, f"Score: {mask_scores[i]:.3f}", (10, 30),
# cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 0), 2)
vis_candidates.append(vis)
vis_final = _overlay_mask(roi_rgb_uint8, mask_final.astype(bool), alpha=0.4)
show_image(
[roi_rgb_uint8] + vis_candidates + [vis_final],
row_plot=2,
titles=[
"Input ROI",
f"Candidate 1 (SAM score: {scores[0]:.3f})",
f"Candidate 2 (SAM score: {scores[1]:.3f})",
f"Candidate 3 (SAM score: {scores[2]:.3f})",
f"Selected & refined (best combined score)"
]
)
return mask_final, _overlay_mask(roi_rgb_uint8, mask_final.astype(bool), alpha=0.4)
def watershed_roi_segmentation(roi_rgb, distance_threshold=0.3, show_steps=True):
"""
Watershed segmentation within ROI: Use distance transform for seeds, select best component.
Args:
roi_rgb: ROI RGB image (extracted region)
distance_threshold: Threshold multiplier for distance transform (0.1-0.5, default=0.3)
show_steps: Whether to show intermediate visualization (default=True)
Returns:
mask: Binary mask (0/255) of the selected object within ROI
final_vis: Visualization with mask overlay
"""
roi_gray = cv2.cvtColor(roi_rgb, cv2.COLOR_RGB2GRAY)
# Otsu thresholding
_, thresh = cv2.threshold(roi_gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
# Morphological opening to remove noise
kernel = np.ones((3, 3), np.uint8)
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)
# Sure background (dilate)
sure_bg = cv2.dilate(opening, kernel, iterations=3)
# Sure foreground via distance transform
dist_transform = cv2.distanceTransform(opening, cv2.DIST_L2, 5)
_, sure_fg = cv2.threshold(dist_transform, distance_threshold * dist_transform.max(), 255, 0)
sure_fg = sure_fg.astype(np.uint8)
# Unknown region
unknown = cv2.subtract(sure_bg, sure_fg)
# Marker labeling
num_labels, markers = cv2.connectedComponents(sure_fg)
markers = markers + 1 # Add 1 so background is not 0 but 1
markers[unknown == 255] = 0 # Mark unknown region as 0
# Watershed
roi_bgr = cv2.cvtColor(roi_rgb, cv2.COLOR_RGB2BGR)
markers_ws = cv2.watershed(roi_bgr, markers.copy())
print(f"Watershed: Found {num_labels} initial components")
# Score each component (exclude background=1 and boundary=-1)
roi_h, roi_w = roi_rgb.shape[:2]
roi_center_y, roi_center_x = roi_h / 2, roi_w / 2
best_component = -1
best_score = -np.inf
component_scores = []
for label in range(2, num_labels + 1): # Start from 2 (1 is background)
component_mask = (markers_ws == label)
# Area score
area = np.sum(component_mask)
area_score = area / (roi_h * roi_w)
# Centroid distance score
if area > 0:
y_coords, x_coords = np.where(component_mask)
centroid_y = np.mean(y_coords)
centroid_x = np.mean(x_coords)
dist_to_center = np.sqrt((centroid_x - roi_center_x)**2 + (centroid_y - roi_center_y)**2)
max_dist = np.sqrt(roi_w**2 + roi_h**2) / 2
centroid_score = 1 - (dist_to_center / max_dist)
else:
centroid_score = 0
# Combined score
combined = area_score * 0.6 + centroid_score * 0.4
component_scores.append((label, combined, area))
if combined > best_score:
best_score = combined
best_component = label
print(f"Component scores: {[(l, f'{s:.3f}') for l, s, _ in component_scores]}")
print(f"Selected component {best_component} with score {best_score:.3f}")
# Create mask for best component
if best_component > 0:
roi_mask = (markers_ws == best_component).astype(np.uint8) * 255
else:
roi_mask = np.zeros((roi_h, roi_w), dtype=np.uint8)
# Morphological cleanup
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
mask_final = cv2.morphologyEx(roi_mask, cv2.MORPH_CLOSE, kernel, iterations=2)
mask_final = cv2.morphologyEx(mask_final, cv2.MORPH_OPEN, kernel, iterations=1)
# Visualization
if show_steps:
# Watershed boundaries visualization
vis_watershed = roi_rgb.copy()
vis_watershed[markers_ws == -1] = [255, 0, 0] # Red boundaries
# Distance transform normalized for display
dist_vis = (dist_transform / dist_transform.max() * 255).astype(np.uint8)
# Final mask overlay
vis_final = _overlay_mask(roi_rgb, mask_final.astype(bool), alpha=0.4)
show_image(
[roi_rgb, thresh, opening, dist_vis, sure_fg, vis_watershed, vis_final],
row_plot=2,
titles=[
"ROI input",
"Otsu threshold",
"Opening (noise removal)",
"Distance transform",
f"Sure FG (thresh={distance_threshold})",
"Watershed boundaries",
"Final selected component"
]
)
return mask_final, _overlay_mask(roi_rgb, mask_final.astype(bool), alpha=0.4)
###----------------------------------- Video Tracking Functions -------------------------------
class MaskTracker:
"""
Base class for mask tracking across video frames.
All trackers follow the same interface:
- init(frame, mask): Initialize tracking from first frame
- update(prev_frame, curr_frame, prev_mask): Track mask to current frame
"""
def init(self, frame, mask):
"""
Initialize tracker with first frame and mask.
Args:
frame: First frame (grayscale uint8)
mask: Initial binary mask (0/255 uint8)
"""
raise NotImplementedError
def update(self, prev_frame, curr_frame, prev_mask):
"""
Update mask from previous frame to current frame.
Args:
prev_frame: Previous frame (grayscale uint8)
curr_frame: Current frame (grayscale uint8)
prev_mask: Previous binary mask (0/255 uint8)
Returns:
curr_mask: Updated binary mask (0/255 uint8)
stats: Dictionary with tracking metrics
"""
raise NotImplementedError
def get_name(self):
"""Return tracker name for logging."""
return self.__class__.__name__
class KLTTracker(MaskTracker):
"""
Track mask using KLT (Kanade-Lucas-Tomasi) feature point tracking.
Tracks a sparse set of feature points on the object, estimates a global
similarity transform (translation + rotation + uniform scale), and warps
the entire mask as one unit. More stable than dense flow for rigid objects.
"""
def __init__(self,
max_points=150,
quality_level=0.01,
min_distance=10,
reinit_threshold=0.3,
refine_kernel_size=5,
refine_iterations=1):
"""
Args:
max_points: Maximum feature points to track
quality_level: Quality threshold for goodFeaturesToTrack (0-1)
min_distance: Minimum distance between feature points (pixels)
reinit_threshold: Reinitialize when points drop below this fraction
refine_kernel_size: Morphology kernel size for cleanup
refine_iterations: Morphology iterations (close+open)
"""
self.max_points = max_points
self.quality_level = quality_level
self.min_distance = min_distance
self.reinit_threshold = reinit_threshold
self.refine_kernel_size = refine_kernel_size
self.refine_iterations = refine_iterations
self.initial_points = None
self.prev_points = None
self.num_initial_points = 0
# KLT parameters
self.lk_params = dict(
winSize=(21, 21),
maxLevel=3,
criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 30, 0.01)
)
def init(self, frame, mask):
"""Initialize feature points inside the mask."""
self._detect_points(frame, mask)
self.num_initial_points = len(self.prev_points) if self.prev_points is not None else 0
def _detect_points(self, frame, mask):
"""Detect feature points inside the mask region."""
# Detect features only inside mask
points = cv2.goodFeaturesToTrack(
frame,
maxCorners=self.max_points,
qualityLevel=self.quality_level,
minDistance=self.min_distance,
mask=mask
)
if points is not None and len(points) > 0:
self.prev_points = points
if self.initial_points is None:
self.initial_points = points.copy()
else:
self.prev_points = None
def update(self, prev_frame, curr_frame, prev_mask):
"""Track points with KLT and warp mask with estimated transform."""
stats = {
'num_points_prev': 0,
'num_points_tracked': 0,
'num_points_inliers': 0,
'transform_estimated': False,
'reinitialized': False
}
# Check if we have points to track
if self.prev_points is None or len(self.prev_points) < 4:
# Need at least 4 points for affine estimation
self._detect_points(curr_frame, prev_mask)
stats['reinitialized'] = True
stats['num_points_prev'] = 0
return prev_mask, stats # Return previous mask as fallback
stats['num_points_prev'] = len(self.prev_points)
# Track points with KLT
curr_points, status, err = cv2.calcOpticalFlowPyrLK(
prev_frame, curr_frame, self.prev_points, None, **self.lk_params
)
# Filter valid points
if status is None:
self._detect_points(curr_frame, prev_mask)
stats['reinitialized'] = True
return prev_mask, stats
good_prev = self.prev_points[status.ravel() == 1]
good_curr = curr_points[status.ravel() == 1]
stats['num_points_tracked'] = len(good_curr)
# Check if we need to reinitialize
min_points_threshold = max(4, int(self.num_initial_points * self.reinit_threshold))
if len(good_curr) < min_points_threshold:
# Reinitialize points on current frame
self._detect_points(curr_frame, prev_mask)
stats['reinitialized'] = True
return prev_mask, stats # Return previous mask as fallback
# Estimate similarity transform (translation + rotation + uniform scale)
transform_matrix, inliers = cv2.estimateAffinePartial2D(
good_prev, good_curr, method=cv2.RANSAC, ransacReprojThreshold=3.0
)
if transform_matrix is None:
# Transform estimation failed, reinitialize
self._detect_points(curr_frame, prev_mask)
stats['reinitialized'] = True
return prev_mask, stats
stats['transform_estimated'] = True
stats['num_points_inliers'] = np.sum(inliers.ravel()) if inliers is not None else len(good_curr)
# Warp mask with estimated transform
h, w = prev_mask.shape
mask_warped = cv2.warpAffine(
prev_mask, transform_matrix, (w, h),
flags=cv2.INTER_LINEAR,
borderMode=cv2.BORDER_CONSTANT,
borderValue=0
)
# Threshold to binary
mask_warped = (mask_warped > 127).astype(np.uint8) * 255
# Light morphological cleanup
if self.refine_iterations > 0:
kernel = cv2.getStructuringElement(
cv2.MORPH_ELLIPSE,
(self.refine_kernel_size, self.refine_kernel_size)
)
mask_warped = cv2.morphologyEx(
mask_warped, cv2.MORPH_CLOSE, kernel,
iterations=self.refine_iterations
)
mask_warped = cv2.morphologyEx(
mask_warped, cv2.MORPH_OPEN, kernel,
iterations=self.refine_iterations
)
# Update points for next frame (use inliers if available)
if inliers is not None:
self.prev_points = good_curr[inliers.ravel() == 1].reshape(-1, 1, 2)
else:
self.prev_points = good_curr.reshape(-1, 1, 2)
return mask_warped, stats
class FlowWarpTracker(MaskTracker):
"""
Track mask using dense optical flow + pixel-wise warping.
Computes dense Farneback optical flow in an ROI around the mask,
warps each pixel independently, then refines with morphology and
component selection.
"""
def __init__(self,
roi_margin=30,
min_mask_area=300,
morph_kernel_size=5,