-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_algorithms.py
More file actions
128 lines (102 loc) · 4.3 KB
/
test_algorithms.py
File metadata and controls
128 lines (102 loc) · 4.3 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
#!/usr/bin/env python
"""
Test script for the new non-deep learning algorithms.
This script tests each of the new algorithms to make sure they work properly.
"""
import os
import sys
import cv2
import numpy as np
import time
import argparse
from typing import Dict, Any, List
# Add the project root to the Python path
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from vigilance_system.detection.algorithms.background_subtraction_detector import BackgroundSubtractionDetector
from vigilance_system.detection.algorithms.mog2_detector import MOG2Detector
from vigilance_system.detection.algorithms.knn_detector import KNNDetector
from vigilance_system.detection.algorithms.svm_classifier_detector import SVMClassifierDetector
def test_detection_algorithms(image_path: str) -> None:
"""
Test all detection algorithms on a single image.
Args:
image_path: Path to the test image
"""
# Load the image
image = cv2.imread(image_path)
if image is None:
print(f"Error: Could not load image from {image_path}")
return
# Create detectors
detectors = {
"Background Subtraction": BackgroundSubtractionDetector(),
"MOG2": MOG2Detector(),
"KNN": KNNDetector(),
"SVM Classifier": SVMClassifierDetector()
}
# Test each detector
for name, detector in detectors.items():
print(f"Testing {name} detector...")
# Make sure the detector has the load_model method
if not hasattr(detector, 'load_model'):
print(f"Error: {name} detector does not have load_model method")
continue
# Call load_model to make sure it works
try:
detector.load_model()
print(f" load_model() successful")
except Exception as e:
print(f" Error in load_model(): {str(e)}")
continue
# Test detection
try:
start_time = time.time()
detections = detector.detect(image)
end_time = time.time()
print(f" detect() successful")
print(f" Found {len(detections)} detections")
print(f" Processing time: {(end_time - start_time) * 1000:.2f} ms")
# Draw detections on the image
result_image = image.copy()
for detection in detections:
# Get bounding box
if hasattr(detection, 'bbox'):
# Detection object
bbox = detection.bbox
confidence = detection.confidence
class_name = detection.class_name
elif isinstance(detection, dict):
# Dictionary
bbox = detection['bbox']
confidence = detection['confidence']
class_name = detection['label']
else:
print(f" Unknown detection format: {type(detection)}")
continue
# Draw bounding box
x1, y1, x2, y2 = map(int, bbox)
cv2.rectangle(result_image, (x1, y1), (x2, y2), (0, 255, 0), 2)
# Draw label
label = f"{class_name}: {confidence:.2f}"
cv2.putText(result_image, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# Save the result image
output_path = f"test_results_{name.lower().replace(' ', '_')}.jpg"
cv2.imwrite(output_path, result_image)
print(f" Result saved to {output_path}")
except Exception as e:
print(f" Error in detect(): {str(e)}")
print("Detection algorithm tests completed")
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(description='Test non-deep learning algorithms')
parser.add_argument('--image', type=str, default='test_image.jpg', help='Path to test image')
args = parser.parse_args()
# Check if the image exists
if not os.path.exists(args.image):
print(f"Error: Image file {args.image} does not exist")
return 1
# Test detection algorithms
test_detection_algorithms(args.image)
return 0
if __name__ == '__main__':
sys.exit(main())