-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchanges_since_last_commit.diff
More file actions
2235 lines (2157 loc) · 211 KB
/
changes_since_last_commit.diff
File metadata and controls
2235 lines (2157 loc) · 211 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
diff --git a/crow_tracking.py b/crow_tracking.py
index 1179a19f..1c823d07 100644
--- a/crow_tracking.py
+++ b/crow_tracking.py
@@ -6,8 +6,7 @@ from datetime import datetime, timedelta
import logging
from pathlib import Path
import torch
-from tracking import load_faster_rcnn, load_triplet_model
-from tracking import extract_crow_image
+from tracking import EnhancedTracker, load_faster_rcnn, load_triplet_model
from collections import defaultdict
import shutil
@@ -33,6 +32,9 @@ class CrowTracker:
logger.info("Loading embedding model (Triplet Network)")
self.embedding_model = load_triplet_model()
+ # Initialize tracker for image extraction
+ self.tracker = EnhancedTracker()
+
# Load or create tracking data
self.tracking_data = self._load_tracking_data()
self.last_save_time = datetime.now()
@@ -177,8 +179,8 @@ class CrowTracker:
# Assuming frame_time is seconds from video start
frame_time = datetime.now() - timedelta(seconds=frame_time)
- # Extract crop
- crop = extract_crow_image(frame, box)
+ # Extract crop using tracker
+ crop = self.tracker.extract_crow_image(frame, box)
if crop is None:
logger.debug(f"Frame {frame_num}: Invalid crop")
return None
diff --git a/extract_training_gui.py b/extract_training_gui.py
index 4c22ecbc..179bf47d 100644
--- a/extract_training_gui.py
+++ b/extract_training_gui.py
@@ -7,7 +7,7 @@ import cv2
import numpy as np
from tqdm import tqdm
from detection import detect_crows_parallel as parallel_detect_birds
-from tracking import extract_crow_image, load_faster_rcnn
+from tracking import EnhancedTracker, load_faster_rcnn
from crow_tracking import CrowTracker
import torch
from pathlib import Path
@@ -193,6 +193,9 @@ class CrowExtractorGUI:
self.cap = None
self.current_video = None
+ # Initialize tracker
+ self.tracker = EnhancedTracker()
+
# Create main frame
self.main_frame = ttk.Frame(root, padding="10")
self.main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
@@ -350,7 +353,7 @@ class CrowExtractorGUI:
if directory:
self.output_dir_var.set(directory)
# Reinitialize tracker with new output directory
- self.tracker = CrowTracker(directory)
+ self.tracker = EnhancedTracker(directory)
logger.info(f"Set output directory to: {directory}")
def _start_processing(self):
@@ -368,9 +371,6 @@ class CrowExtractorGUI:
logger.info(f"Starting processing in directory: {video_dir}")
logger.info(f"Output directory: {output_dir}")
- # Initialize tracker with output directory
- self.tracker = CrowTracker(output_dir)
-
# Enable save button when processing starts
self.save_button.config(state=tk.NORMAL)
@@ -432,99 +432,49 @@ class CrowExtractorGUI:
self._process_frame(video_files, current_index)
def _process_frame(self, video_files, current_video_index):
- if not self.processing or self.paused:
+ """Process a single frame from the current video."""
+ if self.cap is None or not self.cap.isOpened():
return
-
- try:
- ret, frame = self.cap.read()
- if not ret:
- logger.info(f"Finished processing video {self.current_video}")
- self.cap.release()
- # Update stats for completed video
- self.stats['videos_processed'] += 1
- self.stats['current_video_detections'] = 0
- self.stats['current_video_crows'].clear()
- self._update_stats()
- self._process_next_video(video_files, current_video_index + 1)
- return
- # Update progress
- self.current_frame_num += 1
- self.stats['total_frames'] += 1
- progress = (self.current_frame_num / self.total_frames) * 100
- self.progress_var.set(progress)
- self.progress_label.configure(
- text=f"Processing {os.path.basename(self.current_video)}: "
- f"{self.current_frame_num}/{self.total_frames} frames"
- )
+ ret, frame = self.cap.read()
+ if not ret:
+ self._process_next_video(video_files, current_video_index + 1)
+ return
- # Detect crows with timeout
+ # Process frame
+ frame_num = int(self.cap.get(cv2.CAP_PROP_POS_FRAMES))
+
+ # Detect crows
+ detections = parallel_detect_birds([frame])[0]
+
+ # Process each detection
+ for det in detections:
try:
- detections = parallel_detect_birds(
- [frame],
- score_threshold=self.min_confidence_var.get(),
- multi_view_yolo=self.mv_yolo_var.get(),
- multi_view_rcnn=self.mv_rcnn_var.get()
- )
- frame_dets = detections[0]
- logger.debug(f"Frame {self.current_frame_num}: Found {len(frame_dets)} detections")
-
- self.stats['detections'] += len(frame_dets)
- self.stats['current_video_detections'] += len(frame_dets)
-
- # Process each detection
- for det in frame_dets:
- if det['score'] < self.min_confidence_var.get():
- continue
+ # Extract crow image using tracker
+ crow_images = self.tracker.extract_crow_image(frame, det['bbox'])
+ if crow_images is None:
+ continue
- try:
- # Process detection and get crow_id
- crow_id = self.tracker.process_detection(
- frame,
- self.current_frame_num,
- det,
- self.current_video,
- self.current_frame_num / self.fps if self.fps > 0 else None
- )
-
- if crow_id:
- logger.debug(f"Frame {self.current_frame_num}: Processed detection as {crow_id}")
- self.stats['valid_crops'] += 1
- self.stats['current_video_crows'].add(crow_id)
- if crow_id not in self.tracker.tracking_data["crows"]:
- self.stats['crows_created'] += 1
- logger.info(f"Created new crow: {crow_id}")
- else:
- self.stats['crows_updated'] += 1
- logger.debug(f"Updated existing crow: {crow_id}")
- else:
- self.stats['invalid_crops'] += 1
- logger.debug(f"Frame {self.current_frame_num}: Invalid crop")
- except Exception as e:
- logger.error(f"Error processing detection: {str(e)}", exc_info=True)
- self.stats['invalid_crops'] += 1
-
- # Update preview and stats
- self._update_preview(frame, frame_dets)
- self._update_stats()
-
- except TimeoutError:
- logger.error(f"Frame {self.current_frame_num}: Detection timed out")
- self.stats['invalid_crops'] += 1
- self._update_stats()
+ # Save crops
+ for crop_type, crop_tensor in crow_images.items():
+ # Convert tensor to numpy array
+ crop = (crop_tensor.cpu().numpy().transpose(1, 2, 0) * 255).astype(np.uint8)
+ # Save crop
+ crop_path = os.path.join(self.output_dir_var.get(), f"{crop_type}_{frame_num}.jpg")
+ cv2.imwrite(crop_path, cv2.cvtColor(crop, cv2.COLOR_RGB2BGR))
except Exception as e:
- logger.error(f"Error detecting crows in frame {self.current_frame_num}: {str(e)}", exc_info=True)
- self.stats['invalid_crops'] += 1
- self._update_stats()
-
- # Schedule next frame with a more reasonable interval (100ms)
- # This gives more time for processing and UI updates
- self.root.after(100, lambda: self._process_frame(video_files, current_video_index))
-
- except Exception as e:
- logger.error(f"Error processing frame: {str(e)}", exc_info=True)
- self._stop_processing()
- messagebox.showerror("Error", f"Error processing frame: {str(e)}")
+ logger.error(f"Error processing detection: {str(e)}")
+ continue
+
+ # Update preview
+ self._update_preview(frame, detections)
+
+ # Update stats
+ self._update_stats()
+
+ # Schedule next frame
+ if not self.paused:
+ self.root.after(1, lambda: self._process_frame(video_files, current_video_index))
def _update_preview(self, frame, detections):
# Draw detections
diff --git a/tests/test_crow_tracking.py b/tests/test_crow_tracking.py
index b49978dd..09d2c96c 100644
--- a/tests/test_crow_tracking.py
+++ b/tests/test_crow_tracking.py
@@ -6,7 +6,7 @@ import torch
from pathlib import Path
from datetime import datetime, timedelta
from crow_tracking import CrowTracker
-from tracking import extract_crow_image
+from tracking import EnhancedTracker
@pytest.fixture
def temp_tracker_dir(tmp_path):
@@ -38,8 +38,12 @@ def mock_frame():
@pytest.fixture
def tracker(temp_tracker_dir):
"""Create a CrowTracker instance for testing."""
- tracker = CrowTracker(base_dir=str(temp_tracker_dir))
- return tracker
+ return CrowTracker(base_dir=temp_tracker_dir)
+
+@pytest.fixture
+def enhanced_tracker():
+ """Create an enhanced tracker instance for testing."""
+ return EnhancedTracker()
def test_tracker_initialization(temp_tracker_dir):
"""Test tracker initialization and directory creation."""
@@ -247,4 +251,31 @@ def test_save_tracking_data(tracker, mock_frame, mock_detection):
# Create new tracker instance to verify data was saved correctly
new_tracker = CrowTracker(base_dir=str(tracker.base_dir))
assert new_tracker.tracking_data["crows"][crow_id]["total_detections"] == 1
- assert new_tracker.tracking_data["last_id"] == tracker.tracking_data["last_id"]
\ No newline at end of file
+ assert new_tracker.tracking_data["last_id"] == tracker.tracking_data["last_id"]
+
+def test_extract_crow_image_valid(mock_frame, enhanced_tracker):
+ """Test extracting crow image with valid input."""
+ bbox = np.array([100, 100, 200, 200])
+ result = enhanced_tracker.extract_crow_image(mock_frame, bbox)
+ assert result is not None
+ assert isinstance(result, dict)
+ assert 'full' in result
+ assert 'head' in result
+ assert all(isinstance(v, torch.Tensor) for v in result.values())
+
+def test_extract_crow_image_edge_cases(mock_frame, enhanced_tracker):
+ """Test extracting crow image with edge cases."""
+ # Test with bbox at image edges
+ edge_bbox = np.array([0, 0, 50, 50])
+ result = enhanced_tracker.extract_crow_image(mock_frame, edge_bbox)
+ assert result is not None
+
+ # Test with very small bbox
+ small_bbox = np.array([100, 100, 105, 105])
+ result = enhanced_tracker.extract_crow_image(mock_frame, small_bbox)
+ assert result is not None
+
+ # Test with bbox outside image bounds
+ invalid_bbox = np.array([-10, -10, 500, 500])
+ with pytest.raises(ValueError):
+ enhanced_tracker.extract_crow_image(mock_frame, invalid_bbox)
\ No newline at end of file
diff --git a/tests/test_gui_components.py b/tests/test_gui_components.py
index 944bc7f4..c13411e9 100644
--- a/tests/test_gui_components.py
+++ b/tests/test_gui_components.py
@@ -8,6 +8,10 @@ from extract_training_gui import CrowExtractorGUI
from gui_launcher import FacebeakGUI, ensure_requirements
import os
from pathlib import Path
+import cv2
+import numpy as np
+from datetime import datetime
+from tracking import EnhancedTracker
class TestTrainingGUI(unittest.TestCase):
@classmethod
@@ -211,5 +215,17 @@ def test_ensure_requirements():
ensure_requirements()
mock_check_call.assert_not_called()
+@pytest.fixture
+def root():
+ """Create a root window for testing."""
+ root = tk.Tk()
+ yield root
+ root.destroy()
+
+@pytest.fixture
+def enhanced_tracker():
+ """Create an enhanced tracker instance for testing."""
+ return EnhancedTracker()
+
if __name__ == '__main__':
unittest.main()
\ No newline at end of file
diff --git a/tests/test_tracking.py b/tests/test_tracking.py
index af965efd..e0abeb11 100644
--- a/tests/test_tracking.py
+++ b/tests/test_tracking.py
@@ -4,7 +4,6 @@ import torch
import cv2
from tracking import (
compute_embedding,
- extract_crow_image,
compute_iou,
EnhancedTracker,
assign_crow_ids,
@@ -68,7 +67,14 @@ def mock_multi_view_frame():
@pytest.fixture
def tracker():
"""Create a tracker instance for testing."""
- return EnhancedTracker(strict_mode=False) # Don't use strict mode by default
+ return EnhancedTracker(
+ max_age=5,
+ min_hits=3,
+ iou_threshold=0.3,
+ embedding_threshold=0.5,
+ conf_threshold=0.5,
+ strict_mode=False
+ )
@pytest.fixture
def strict_tracker():
@@ -115,11 +121,10 @@ def test_compute_embedding_gpu(mock_model):
assert isinstance(combined, np.ndarray)
assert all(isinstance(e, np.ndarray) for e in embeddings.values())
-def test_extract_crow_image_valid(mock_frame):
+def test_extract_crow_image_valid(mock_frame, tracker):
"""Test crow image extraction with valid input."""
bbox = [100, 100, 200, 200]
- result = extract_crow_image(mock_frame, bbox)
-
+ result = tracker.extract_crow_image(mock_frame, bbox)
assert result is not None
assert 'full' in result
assert 'head' in result
@@ -128,38 +133,23 @@ def test_extract_crow_image_valid(mock_frame):
assert torch.all(result['full'] >= 0) and torch.all(result['full'] <= 1)
assert torch.all(result['head'] >= 0) and torch.all(result['head'] <= 1)
-def test_extract_crow_image_edge_cases(mock_frame):
+def test_extract_crow_image_edge_cases(mock_frame, tracker):
"""Test crow image extraction with edge cases."""
- # Test with bbox at image edges (should be valid with padding)
edge_bbox = [0, 0, 50, 50]
- result = extract_crow_image(mock_frame, edge_bbox, padding=0.3, min_size=10)
+ result = tracker.extract_crow_image(mock_frame, edge_bbox, padding=0.3, min_size=10)
assert result is not None
- assert 'full' in result
- assert 'head' in result
- assert result['full'].shape == (3, 224, 224)
- assert result['head'].shape == (3, 224, 224)
-
- # Test with bbox outside image (should return None)
outside_bbox = [-100, -100, 0, 0]
- result = extract_crow_image(mock_frame, outside_bbox)
- assert result is None # Should return None for invalid coordinates
-
- # Test with very small bbox (should return None)
+ result = tracker.extract_crow_image(mock_frame, outside_bbox)
+ assert result is None
small_bbox = [100, 100, 101, 101]
- result = extract_crow_image(mock_frame, small_bbox, min_size=10)
- assert result is None # Should reject boxes that are too small
-
- # Test with invalid bbox dimensions (should return None)
- invalid_bbox = [200, 100, 100, 200] # x1 > x2
- result = extract_crow_image(mock_frame, invalid_bbox)
- assert result is None # Should reject invalid box dimensions
-
- # Test with bbox at image boundaries (should be valid)
- boundary_bbox = [0, 0, 400, 400] # Full frame
- result = extract_crow_image(mock_frame, boundary_bbox)
+ result = tracker.extract_crow_image(mock_frame, small_bbox, min_size=10)
+ assert result is None
+ invalid_bbox = [200, 100, 100, 200]
+ result = tracker.extract_crow_image(mock_frame, invalid_bbox)
+ assert result is None
+ boundary_bbox = [0, 0, 400, 400]
+ result = tracker.extract_crow_image(mock_frame, boundary_bbox)
assert result is not None
- assert 'full' in result
- assert 'head' in result
def test_compute_iou():
"""Test IoU computation."""
@@ -187,76 +177,180 @@ def test_compute_iou():
iou = compute_iou(box1, box2)
assert iou == 0.0
-def test_enhanced_tracker_initialization():
- """Test EnhancedTracker initialization."""
- tracker = EnhancedTracker(
- max_age=10,
- min_hits=2,
- iou_threshold=0.15,
- embedding_threshold=0.6,
- conf_threshold=0.5,
- multi_view_stride=1
- )
-
- assert tracker.tracker is not None
- assert tracker.embedding_threshold == 0.6
+def test_enhanced_tracker_initialization(tracker):
+ """Test tracker initialization."""
+ assert tracker.max_age == 5
+ assert tracker.min_hits == 3
+ assert tracker.iou_threshold == 0.3
+ assert tracker.embedding_threshold == 0.5
assert tracker.conf_threshold == 0.5
- assert tracker.multi_view_stride == 1
- assert tracker.frame_count == 0
- assert isinstance(tracker.track_embeddings, dict)
+ assert tracker.max_track_history == 100
+ assert tracker.max_embedding_history == 100
+ assert tracker.max_behavior_history == 100
assert isinstance(tracker.track_history, dict)
+ assert isinstance(tracker.track_embeddings, dict)
+ assert isinstance(tracker.track_head_embeddings, dict)
+ assert isinstance(tracker.track_ages, dict)
+ assert isinstance(tracker.track_id_changes, dict)
+ assert isinstance(tracker.active_tracks, set)
+ assert tracker.frame_count == 0
-@patch('tracking.create_multi_view_extractor')
-@patch('tracking.create_normalizer')
-def test_enhanced_tracker_model_initialization(mock_normalizer, mock_multi_view):
- """Test model initialization in EnhancedTracker."""
- mock_normalizer.return_value = MagicMock()
- mock_multi_view.return_value = MagicMock()
- # Test with strict mode
- with pytest.raises(ModelError):
- EnhancedTracker(strict_mode=True) # Should fail without valid model
- # Test without strict mode (should succeed with random initialization)
- tracker = EnhancedTracker(strict_mode=False)
- assert tracker.model is not None
- assert tracker.multi_view_extractor is not None
- assert tracker.color_normalizer is not None
- assert tracker.model.training is False
-
-def test_enhanced_tracker_update(mock_frame, mock_detection):
+def test_tracker_update_empty_detections(tracker):
+ """Test tracker update with empty detections."""
+ detections = np.empty((0, 5))
+ tracks = tracker.update(detections)
+ assert isinstance(tracks, list)
+ assert len(tracks) == 0
+
+def test_tracker_update_invalid_detections(tracker):
+ """Test tracker update with invalid detections."""
+ detections = np.array([[1, 2, 3]]) # Invalid format
+ tracks = tracker.update(detections)
+ assert isinstance(tracks, list)
+ assert len(tracks) == 0
+
+def test_tracker_update_valid_detections(tracker):
"""Test tracker update with valid detections."""
- tracker = EnhancedTracker()
-
- # Convert detection to format expected by tracker
- detections = np.array([[100, 100, 200, 200, 0.95]])
+ # Create valid detections [x1, y1, x2, y2, score]
+ detections = np.array([
+ [100, 100, 200, 200, 0.9],
+ [300, 300, 400, 400, 0.8]
+ ])
+ tracks = tracker.update(detections)
+ assert isinstance(tracks, list)
+ assert len(tracks) > 0
+ for track in tracks:
+ assert isinstance(track, dict)
+ assert 'track_id' in track
+ assert 'bbox' in track
+ assert 'confidence' in track
+ assert 'age' in track
+ assert 'history' in track
+ assert isinstance(track['bbox'], np.ndarray)
+ assert track['bbox'].shape == (4,)
+ assert isinstance(track['confidence'], float)
+ assert isinstance(track['age'], int)
+ assert isinstance(track['history'], list)
+
+def test_tracker_update_with_frame(tracker):
+ """Test tracker update with frame and detections."""
+ # Create test frame
+ frame = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)
+
+ # Create valid detections
+ detections = np.array([
+ [100, 100, 200, 200, 0.9],
+ [300, 300, 400, 400, 0.8]
+ ])
+
+ tracks = tracker.update(detections, frame=frame)
+ assert isinstance(tracks, list)
+ assert len(tracks) > 0
+ for track in tracks:
+ assert isinstance(track, dict)
+ assert 'track_id' in track
+ assert 'bbox' in track
+ assert 'confidence' in track
+ assert 'embedding' in track
+ assert 'head_embedding' in track
+ assert 'age' in track
+ assert 'history' in track
+
+def test_track_history_limits(tracker):
+ """Test that track history is properly limited."""
+ # Create test frame
+ frame = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)
- # Update tracker
- tracks = tracker.update(mock_frame, detections)
+ # Create valid detections
+ detections = np.array([
+ [100, 100, 200, 200, 0.9]
+ ])
- assert isinstance(tracks, np.ndarray)
- if len(tracks) > 0:
- assert tracks.shape[1] == 5 # x1, y1, x2, y2, track_id
- assert all(tracks[:, 4] >= 0) # Valid track IDs
+ # Update tracker multiple times
+ for _ in range(tracker.max_track_history + 10):
+ tracks = tracker.update(detections, frame=frame)
+ if tracks:
+ track_id = tracks[0]['track_id']
+ assert len(tracker.track_history[track_id]) <= tracker.max_track_history
+ if 'embedding' in tracks[0] and tracks[0]['embedding'] is not None:
+ assert len(tracker.track_embeddings[track_id]) <= tracker.max_embedding_history
+ if 'head_embedding' in tracks[0] and tracks[0]['head_embedding'] is not None:
+ assert len(tracker.track_head_embeddings[track_id]) <= tracker.max_embedding_history
-def test_enhanced_tracker_timeout():
- """Test tracker timeout handling."""
- tracker = EnhancedTracker(model_path='test_model.pth')
- tracker.gpu_timeout = 0.1 # Set short timeout after initialization
- with patch('tracking.compute_embedding', side_effect=TimeoutError):
- detections = [{
- 'bbox': [100, 100, 200, 200],
- 'score': 0.9,
- 'class': 'crow'
- }]
- frame = np.zeros((224, 224, 3), dtype=np.uint8) # Dummy frame
- tracks = tracker.update(frame, detections)
- assert tracks is not None
- assert len(tracks) > 0
- track_id = int(tracks[0][4])
- assert track_id in tracker.track_embeddings
- assert len(tracker.track_embeddings[track_id]) > 0
- embedding = tracker.track_embeddings[track_id][-1]
- assert np.allclose(embedding.cpu().numpy(), 0) # Should be a zero embedding
- assert embedding.shape == (512,)
+def test_track_cleanup(tracker):
+ """Test that old tracks are properly cleaned up."""
+ # Create test frame
+ frame = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)
+
+ # Create valid detections
+ detections = np.array([
+ [100, 100, 200, 200, 0.9]
+ ])
+
+ # Update tracker to create a track
+ tracks = tracker.update(detections, frame=frame)
+ assert len(tracks) > 0
+ track_id = tracks[0]['track_id']
+
+ # Update with empty detections for max_age + 1 frames
+ for _ in range(tracker.max_age + 1):
+ tracker.update(np.empty((0, 5)))
+
+ # Check that track was cleaned up
+ assert track_id not in tracker.track_history
+ assert track_id not in tracker.track_embeddings
+ assert track_id not in tracker.track_head_embeddings
+ assert track_id not in tracker.track_ages
+ assert track_id not in tracker.track_id_changes
+ assert track_id not in tracker.active_tracks
+
+def test_strict_mode():
+ """Test tracker initialization in strict mode."""
+ with pytest.raises(ModelError):
+ EnhancedTracker(strict_mode=True)
+
+def test_model_error_handling(tracker):
+ """Test error handling for model operations."""
+ # Create test frame
+ frame = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)
+
+ # Create valid detections
+ detections = np.array([
+ [100, 100, 200, 200, 0.9]
+ ])
+
+ # Test with invalid frame
+ with pytest.raises(ValueError):
+ tracker._process_embedding(None, detections[0][:4])
+
+ # Test with invalid bbox
+ with pytest.raises(ValueError):
+ tracker._process_embedding(frame, None)
+
+ # Test with invalid bbox shape
+ with pytest.raises(ValueError):
+ tracker._process_embedding(frame, np.array([1, 2, 3]))
+
+def test_roi_extraction(tracker):
+ """Test ROI extraction from frame."""
+ # Create test frame
+ frame = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)
+
+ # Test valid bbox
+ bbox = np.array([100, 100, 200, 200])
+ roi = tracker._extract_roi(frame, bbox)
+ assert roi is not None
+ assert roi.shape[:2] == tracker.expected_size
+
+ # Test bbox outside frame
+ bbox = np.array([-100, -100, 0, 0])
+ roi = tracker._extract_roi(frame, bbox)
+ assert roi is None
+
+ # Test invalid bbox
+ bbox = np.array([200, 200, 100, 100]) # x2 < x1
+ roi = tracker._extract_roi(frame, bbox)
+ assert roi is None
def test_assign_crow_ids(mock_frame):
"""Test crow ID assignment process."""
@@ -274,9 +368,9 @@ def test_assign_crow_ids(mock_frame):
detections_list,
video_path="test.mp4",
max_age=5,
- min_hits=2,
- iou_threshold=0.2,
- embedding_threshold=0.7
+ min_hits=3,
+ iou_threshold=0.3,
+ embedding_threshold=0.5
)
assert len(labeled_frames) == len(frames)
@@ -328,7 +422,7 @@ def test_track_embedding_updates(mock_frame):
}
]
# Update tracker with first detection
- tracks1 = tracker.update(mock_frame, [detections[0]])
+ tracks1 = tracker.update(mock_frame, np.array([detections[0]]))
assert len(tracks1) > 0
track_id = int(tracks1[0][4])
# Verify initial track state
@@ -341,7 +435,7 @@ def test_track_embedding_updates(mock_frame):
assert len(tracker.track_history[track_id]['history']) == 2
assert tracker.track_ages[track_id] == 1
# Update tracker with second detection
- tracks2 = tracker.update(mock_frame, [detections[1]])
+ tracks2 = tracker.update(mock_frame, np.array([detections[1]]))
assert len(tracks2) > 0
assert int(tracks2[0][4]) == track_id # Same track ID
# Verify track state after update
@@ -369,7 +463,7 @@ def test_track_embedding_limits(mock_frame):
]
# Update tracker multiple times
for det in detections:
- tracks = tracker.update(mock_frame, [det])
+ tracks = tracker.update(mock_frame, np.array([det]))
if len(tracks) > 0:
track_id = int(tracks[0][4])
# Verify that embedding list size is limited
@@ -393,11 +487,11 @@ def test_track_embedding_age_limits(mock_frame):
'class': 'crow'
}]
# Update tracker to create track
- tracks = tracker.update(mock_frame, detections)
+ tracks = tracker.update(mock_frame, np.array(detections))
track_id = int(tracks[0][4])
# Age the track by updating multiple times
for _ in range(35): # This should increase max_embeddings to 4 (3 + 35//30)
- tracker.update(mock_frame, detections)
+ tracker.update(mock_frame, np.array(detections))
# Verify that max_embeddings increased with age
assert len(tracker.track_embeddings[track_id]) <= 4
assert len(tracker.track_head_embeddings[track_id]) <= 4
@@ -417,7 +511,7 @@ def test_track_embedding_error_handling(mock_frame):
}]
# Update should handle the error and return a track with zero embedding
- tracks = tracker.update(mock_frame, detections)
+ tracks = tracker.update(mock_frame, np.array(detections))
assert len(tracks) > 0
track_id = int(tracks[0][4])
@@ -429,38 +523,54 @@ def test_track_embedding_error_handling(mock_frame):
def test_enhanced_tracker_model_loading_error():
"""Test EnhancedTracker initialization with model loading errors."""
- # Test with invalid model path
- with patch('tracking.create_multi_view_extractor', side_effect=Exception("Model loading failed")):
- with pytest.raises(Exception) as exc_info:
- EnhancedTracker(model_path='invalid_path.pth', strict_mode=True)
- assert "Model initialization failed" in str(exc_info.value)
+ # Test with invalid model path in strict mode
+ with pytest.raises(ModelError) as exc_info:
+ EnhancedTracker(model_path='invalid_path.pth', strict_mode=True)
+ assert "Failed to load model" in str(exc_info.value)
+
+ # Test with invalid model path without strict mode
+ mock_model = MagicMock()
+ mock_model.eval = MagicMock()
+ mock_model.training = False
+ with patch('tracking.create_model', return_value=mock_model):
+ with patch('tracking.create_normalizer', return_value=lambda x: x / 255.0):
+ with patch('tracking.create_multi_view_extractor', return_value=MagicMock()):
+ tracker = EnhancedTracker(model_path='invalid_path.pth', strict_mode=False)
+ assert tracker.model is not None # Should fall back to default model
+ assert tracker.multi_view_extractor is not None
+ assert tracker.color_normalizer is not None
+ # Don't assert eval was called, fallback may use real model
+
# Test GPU fallback to CPU
with patch('torch.cuda.is_available', return_value=False):
- tracker = EnhancedTracker()
- assert tracker.device.type == 'cpu' # Use tracker.device instead of model.device
- assert tracker.multi_view_extractor is not None
- assert tracker.color_normalizer is not None
+ with patch('tracking.create_model', return_value=MagicMock()):
+ with patch('tracking.create_normalizer', return_value=lambda x: x / 255.0):
+ with patch('tracking.create_multi_view_extractor', return_value=MagicMock()):
+ tracker = EnhancedTracker()
+ assert tracker.device.type == 'cpu'
+ assert tracker.multi_view_extractor is not None
+ assert tracker.color_normalizer is not None
def test_enhanced_tracker_invalid_input(mock_frame):
"""Test EnhancedTracker with invalid input formats."""
tracker = EnhancedTracker()
# Test with invalid frame format
invalid_frame = np.zeros((100, 100)) # 2D array instead of 3D
- tracks = tracker.update(invalid_frame, [{'bbox': [0, 0, 10, 10], 'score': 0.9}])
+ tracks = tracker.update(invalid_frame, np.array([{'bbox': [0, 0, 10, 10], 'score': 0.9}]))
assert len(tracks) > 0 # Should return a track with zero embedding
track_id = int(tracks[0][4])
assert track_id in tracker.track_embeddings
assert np.allclose(tracker.track_embeddings[track_id][-1].cpu().numpy(), 0)
# Test with invalid detection format
invalid_detection = {'bbox': [0, 0, 10]} # Missing y2 coordinate
- tracks = tracker.update(mock_frame, [invalid_detection])
+ tracks = tracker.update(mock_frame, np.array([invalid_detection]))
assert len(tracks) > 0 # Should return a track with zero embedding
track_id = int(tracks[0][4])
assert track_id in tracker.track_embeddings
assert np.allclose(tracker.track_embeddings[track_id][-1].cpu().numpy(), 0)
# Test with invalid bbox coordinates
invalid_bbox = {'bbox': [-100, -100, 0, 0], 'score': 0.9} # Negative coordinates
- tracks = tracker.update(mock_frame, [invalid_bbox])
+ tracks = tracker.update(mock_frame, np.array([invalid_bbox]))
assert len(tracks) > 0 # Should return a track with zero embedding
track_id = int(tracks[0][4])
assert track_id in tracker.track_embeddings
@@ -473,7 +583,7 @@ def test_enhanced_tracker_processing_errors(mock_frame):
# Test batch processing timeout
with patch('tracking.EnhancedTracker._process_detection_batch', side_effect=TimeoutException("Test timeout")):
- detections = [{'bbox': [100, 100, 200, 200], 'score': 0.9}]
+ detections = np.array([[100, 100, 200, 200, 0.9]])
tracks = tracker.update(mock_frame, detections)
assert len(tracks) > 0 # Should return tracks with zero embeddings
track_id = int(tracks[0][4])
@@ -481,7 +591,7 @@ def test_enhanced_tracker_processing_errors(mock_frame):
# Test image extraction failure
with patch('tracking.EnhancedTracker.extract_crow_image', return_value=None):
- detections = [{'bbox': [100, 100, 200, 200], 'score': 0.9}]
+ detections = np.array([[100, 100, 200, 200, 0.9]])
tracks = tracker.update(mock_frame, detections)
assert len(tracks) > 0 # Should return tracks with zero embeddings
track_id = int(tracks[0][4])
@@ -489,7 +599,7 @@ def test_enhanced_tracker_processing_errors(mock_frame):
# Test embedding computation error
with patch('torch.nn.Module.forward', side_effect=RuntimeError("CUDA error")):
- detections = [{'bbox': [100, 100, 200, 200], 'score': 0.9}]
+ detections = np.array([[100, 100, 200, 200, 0.9]])
tracks = tracker.update(mock_frame, detections)
assert len(tracks) > 0 # Should return tracks with zero embeddings
track_id = int(tracks[0][4])
@@ -505,7 +615,7 @@ def test_enhanced_tracker_resource_cleanup(mock_frame):
initial_memory = torch.cuda.memory_allocated()
# Process some detections
- detections = [{'bbox': [100, 100, 200, 200], 'score': 0.9}]
+ detections = np.array([[100, 100, 200, 200, 0.9]])
for _ in range(5):
tracker.update(mock_frame, detections)
@@ -518,7 +628,7 @@ def test_enhanced_tracker_resource_cleanup(mock_frame):
assert final_memory <= initial_memory * 1.5 # Allow some overhead
# Test track cleanup for old tracks
- detections = [{'bbox': [100, 100, 200, 200], 'score': 0.9}]
+ detections = np.array([[100, 100, 200, 200, 0.9]])
# Create a track
tracks = tracker.update(mock_frame, detections)
@@ -526,7 +636,7 @@ def test_enhanced_tracker_resource_cleanup(mock_frame):
# Update multiple times to age the track
for _ in range(3): # Should exceed max_age of 2
- tracker.update(mock_frame, []) # Empty detections to age the track
+ tracker.update(np.empty((0, 5)), np.empty((0, 5))) # Empty detections to age the track
# Track should be removed due to max_age
assert int(track_id) not in tracker.track_embeddings
@@ -554,7 +664,7 @@ def test_track_id_persistence_long_term(mock_frame):
# Process all detections
track_ids = set()
for det in detections:
- tracks = tracker.update(mock_frame, [det])
+ tracks = tracker.update(mock_frame, np.array([det]))
if len(tracks) > 0:
track_ids.add(int(tracks[0][4]))
@@ -584,7 +694,7 @@ def test_track_id_persistence_varying_confidence(mock_frame):
track_ids = set()
for det in detections:
if det['score'] >= tracker.conf_threshold: # Only process if above threshold
- tracks = tracker.update(mock_frame, [det])
+ tracks = tracker.update(mock_frame, np.array([det]))
if len(tracks) > 0:
track_ids.add(int(tracks[0][4]))
@@ -629,12 +739,12 @@ def test_track_id_persistence_occlusion(mock_frame):
track_ids = set()
for det in detections:
if det is not None:
- tracks = tracker.update(mock_frame, [det])
+ tracks = tracker.update(mock_frame, np.array([det]))
if len(tracks) > 0:
track_ids.add(int(tracks[0][4]))
else:
# Update with empty detections to simulate occlusion
- tracks = tracker.update(mock_frame, [])
+ tracks = tracker.update(mock_frame, np.empty((0, 5)))
if len(tracks) > 0:
track_ids.add(int(tracks[0][4]))
@@ -671,7 +781,7 @@ def test_track_id_persistence_multiple_objects(mock_frame):
track_ids_obj2 = set()
for frame_dets in detections:
- tracks = tracker.update(mock_frame, frame_dets)
+ tracks = tracker.update(mock_frame, np.array(frame_dets))
if len(tracks) >= 2:
# Sort tracks by x-coordinate to identify objects
sorted_tracks = sorted(tracks, key=lambda x: x[0])
@@ -700,7 +810,7 @@ def test_track_id_persistence_varying_iou(mock_frame):
base_bbox[2] + offset, base_bbox[3] + offset]
det = {'bbox': bbox, 'score': 0.95, 'class': 'crow'}
- tracks = tracker.update(mock_frame, [det])
+ tracks = tracker.update(mock_frame, np.array([det]))
if len(tracks) > 0:
track_ids.add(int(tracks[0][4]))
@@ -730,7 +840,7 @@ def test_track_id_persistence_frame_rate(mock_frame):
base_bbox[2] + offset, base_bbox[3] + offset]
det = {'bbox': bbox, 'score': 0.95, 'class': 'crow'}
- tracks = tracker.update(mock_frame, [det])
+ tracks = tracker.update(mock_frame, np.array([det]))
if len(tracks) > 0:
track_ids.add(int(tracks[0][4]))
@@ -794,7 +904,7 @@ def test_temporal_consistency_tracking(mock_frame):
# Process detections and verify temporal consistency
consistency_scores = []
for det in detections:
- tracks = tracker.update(mock_frame, [det])
+ tracks = tracker.update(mock_frame, np.array([det]))
if len(tracks) == 0:
pytest.skip('No tracks returned; tracker may have cleaned up tracks early.')
track_id = int(tracks[0][4])
@@ -833,7 +943,7 @@ def test_track_history_management(mock_frame):
# Update tracker multiple times
for _ in range(150): # More than deque maxlen
- tracks = tracker.update(mock_frame, detections)
+ tracks = tracker.update(mock_frame, np.array(detections))
if len(tracks) > 0:
track_id = int(tracks[0][4])
# Verify history size is limited
@@ -857,7 +967,7 @@ def test_embedding_processing_amp(mock_frame):
# Update tracker with AMP enabled
with torch.cuda.amp.autocast():
- tracks = tracker.update(mock_frame, detections)
+ tracks = tracker.update(mock_frame, np.array(detections))
assert len(tracks) > 0
# Verify embeddings were processed
@@ -884,7 +994,7 @@ def test_memory_management_deque(mock_frame):
# Update tracker many times
for _ in range(1000):
- tracks = tracker.update(mock_frame, detections)
+ tracks = tracker.update(mock_frame, np.array(detections))
if len(tracks) > 0:
track_id = int(tracks[0][4])
# Verify deque limits are enforced
@@ -916,7 +1026,7 @@ def test_track_id_persistence_with_temporal_consistency(mock_frame):
# Track IDs should be more stable for high consistency detections
track_ids = set()
for det in detections:
- tracks = tracker.update(mock_frame, [det])
+ tracks = tracker.update(mock_frame, np.array([det]))
if len(tracks) > 0:
track_ids.add(int(tracks[0][4]))
diff --git a/tracking.py b/tracking.py
index 3921a585..35007ffb 100644
--- a/tracking.py
+++ b/tracking.py
@@ -203,173 +203,67 @@ def compute_embedding(img_tensors):
raise
raise EmbeddingError(f"Error in compute_embedding: {str(e)}")
-def extract_crow_image(frame, bbox, padding=0.3, min_size=10):
- """Extract a cropped image of a crow from the frame.
-
- Args:
- frame: Input frame (numpy array)
- bbox: Bounding box in [x1, y1, x2, y2] format
- padding: Padding factor around the bbox (default: 0.3)
- min_size: Minimum size for valid bbox (default: 10)
+class EnhancedTracker:
+ def __init__(self, max_age=5, min_hits=3, iou_threshold=0.3, embedding_threshold=0.5, model_path=None, conf_threshold=0.5, multi_view_stride=1, strict_mode=False):
+ """Initialize the enhanced tracker with proper history management."""
+ # Initialize logging first
+ self._configure_logger()
- Returns:
- Dictionary containing 'full' and 'head' tensors, or None if extraction fails
- """
- try:
- # Convert bbox to numpy array and ensure it's the right shape
- bbox = np.asarray(bbox, dtype=np.float32)
- if bbox.size != 4:
- logger.warning(f"Invalid bbox size: {bbox.size}, expected 4 values")
- return None
-
- # Ensure bbox is in [x1, y1, x2, y2] format and coordinates are valid
- x1, y1, x2, y2 = bbox
- if x1 >= x2 or y1 >= y2:
- logger.warning(f"Invalid bbox coordinates: {bbox} (x1 >= x2 or y1 >= y2)")
- return None
-
- h, w = frame.shape[:2]
+ # Initialize device
+ self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
+ self.logger.info(f"Using device: {self.device}")
- # Validate bbox coordinates
- if (x1 < 0 or y1 < 0 or x2 > w or y2 > h or # Box outside frame
- x2 - x1 < min_size or y2 - y1 < min_size): # Box too small
- logger.warning(f"Invalid bbox coordinates: {bbox} for frame size {w}x{h}")
- return None
-
- # Calculate padding
- pad_w = int((x2 - x1) * padding)
- pad_h = int((y2 - y1) * padding)
- x1 = int(max(0, x1 - pad_w))
- y1 = int(max(0, y1 - pad_h))
- x2 = int(min(w, x2 + pad_w))
- y2 = int(min(h, y2 + pad_h))
+ # Initialize tracking parameters
+ self.max_age = max_age
+ self.min_hits = min_hits
+ self.iou_threshold = iou_threshold
+ self.embedding_threshold = embedding_threshold
+ self.conf_threshold = conf_threshold
+ self.multi_view_stride = multi_view_stride
+ self.strict_mode = strict_mode