File size: 7,035 Bytes
0465b15 | 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 | #!/usr/bin/env python3
"""
Test script for the YOLO Object Detection application.
This script tests the core functionality without requiring a webcam.
"""
import sys
import os
import numpy as np
import cv2
# Add src directory to path
sys.path.append(os.path.join(os.path.dirname(__file__), 'src'))
def test_imports():
"""Test if all required modules can be imported."""
print("Testing imports...")
try:
from detection.yolo_detector import YOLODetector
print("β
YOLODetector imported successfully")
except ImportError as e:
print(f"β Failed to import YOLODetector: {e}")
return False
try:
from detection.webcam_capture import WebcamCapture, get_available_cameras
print("β
WebcamCapture imported successfully")
except ImportError as e:
print(f"β Failed to import WebcamCapture: {e}")
return False
try:
from utils.config import app_config
print("β
Configuration imported successfully")
except ImportError as e:
print(f"β Failed to import configuration: {e}")
return False
try:
from utils.helpers import resize_image, format_detection_info
print("β
Helper functions imported successfully")
except ImportError as e:
print(f"β Failed to import helpers: {e}")
return False
try:
from utils.error_handler import ErrorHandler
print("β
Error handler imported successfully")
except ImportError as e:
print(f"β Failed to import error handler: {e}")
return False
return True
def test_detector():
"""Test YOLO detector with a dummy image."""
print("\nTesting YOLO detector...")
try:
from detection.yolo_detector import YOLODetector
# Create a dummy image (640x480 RGB)
dummy_image = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)
# Initialize detector
print("Initializing YOLOv8n detector...")
detector = YOLODetector("yolov8n.pt", 0.5)
if detector.model is None:
print("β Failed to load YOLO model")
return False
print("β
YOLO model loaded successfully")
# Test detection on dummy image
print("Running detection on dummy image...")
detections = detector.detect_objects(dummy_image)
print(f"β
Detection completed. Found {len(detections)} objects")
# Test drawing detections
if detections:
annotated_image = detector.draw_detections(dummy_image, detections)
print("β
Detection drawing completed")
# Test statistics
stats = detector.get_detection_stats(detections)
print(f"β
Statistics generated: {stats}")
return True
except Exception as e:
print(f"β Detector test failed: {e}")
return False
def test_webcam_availability():
"""Test webcam availability."""
print("\nTesting webcam availability...")
try:
from detection.webcam_capture import get_available_cameras, test_camera_availability
available_cameras = get_available_cameras()
print(f"Available cameras: {available_cameras}")
if available_cameras:
print("β
At least one camera is available")
# Test first available camera
camera_index = available_cameras[0]
if test_camera_availability(camera_index):
print(f"β
Camera {camera_index} is working")
else:
print(f"β οΈ Camera {camera_index} detected but not working properly")
else:
print("β οΈ No cameras detected (this is normal in some environments)")
return True
except Exception as e:
print(f"β Webcam test failed: {e}")
return False
def test_configuration():
"""Test configuration system."""
print("\nTesting configuration...")
try:
from utils.config import app_config
# Test configuration loading
print(f"β
Configuration loaded")
print(f" - Default model: {app_config.detection.model_name}")
print(f" - Confidence threshold: {app_config.detection.confidence_threshold}")
print(f" - Available models: {len(app_config.available_models)}")
# Test validation
errors = app_config.validate_config()
if not errors:
print("β
Configuration validation passed")
else:
print(f"β οΈ Configuration validation issues: {errors}")
return True
except Exception as e:
print(f"β Configuration test failed: {e}")
return False
def test_helpers():
"""Test helper functions."""
print("\nTesting helper functions...")
try:
from utils.helpers import resize_image, calculate_iou, create_color_palette
# Test image resizing
dummy_image = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)
resized = resize_image(dummy_image, 320, 240)
print(f"β
Image resize: {dummy_image.shape} -> {resized.shape}")
# Test IoU calculation
box1 = [10, 10, 50, 50]
box2 = [30, 30, 70, 70]
iou = calculate_iou(box1, box2)
print(f"β
IoU calculation: {iou:.3f}")
# Test color palette
colors = create_color_palette(10)
print(f"β
Color palette created: {len(colors)} colors")
return True
except Exception as e:
print(f"β Helper functions test failed: {e}")
return False
def main():
"""Run all tests."""
print("π― YOLO Object Detection - Application Test Suite")
print("=" * 50)
tests = [
("Import Test", test_imports),
("Configuration Test", test_configuration),
("Helper Functions Test", test_helpers),
("Webcam Availability Test", test_webcam_availability),
("YOLO Detector Test", test_detector),
]
passed = 0
total = len(tests)
for test_name, test_func in tests:
print(f"\nπ Running {test_name}...")
try:
if test_func():
passed += 1
print(f"β
{test_name} PASSED")
else:
print(f"β {test_name} FAILED")
except Exception as e:
print(f"β {test_name} FAILED with exception: {e}")
print("\n" + "=" * 50)
print(f"π Test Results: {passed}/{total} tests passed")
if passed == total:
print("π All tests passed! The application is ready to use.")
print("\nTo run the application:")
print(" streamlit run app.py")
else:
print("β οΈ Some tests failed. Please check the error messages above.")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
|