midlajvalappil/Real-time_Object_Detection_with_YOLO
0
1#!/usr/bin/env python32"""3Test script for the YOLO Object Detection application.4This script tests the core functionality without requiring a webcam.5"""6 7import sys8import os9import numpy as np10import cv211 12# Add src directory to path13sys.path.append(os.path.join(os.path.dirname(__file__), 'src'))14 15def test_imports():16 """Test if all required modules can be imported."""17 print("Testing imports...")18 19 try:20 from detection.yolo_detector import YOLODetector21 print("✅ YOLODetector imported successfully")22 except ImportError as e:23 print(f"❌ Failed to import YOLODetector: {e}")24 return False25 26 try:27 from detection.webcam_capture import WebcamCapture, get_available_cameras28 print("✅ WebcamCapture imported successfully")29 except ImportError as e:30 print(f"❌ Failed to import WebcamCapture: {e}")31 return False32 33 try:34 from utils.config import app_config35 print("✅ Configuration imported successfully")36 except ImportError as e:37 print(f"❌ Failed to import configuration: {e}")38 return False39 40 try:41 from utils.helpers import resize_image, format_detection_info42 print("✅ Helper functions imported successfully")43 except ImportError as e:44 print(f"❌ Failed to import helpers: {e}")45 return False46 47 try:48 from utils.error_handler import ErrorHandler49 print("✅ Error handler imported successfully")50 except ImportError as e:51 print(f"❌ Failed to import error handler: {e}")52 return False53 54 return True55 56def test_detector():57 """Test YOLO detector with a dummy image."""58 print("\nTesting YOLO detector...")59 60 try:61 from detection.yolo_detector import YOLODetector62 63 # Create a dummy image (640x480 RGB)64 dummy_image = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)65 66 # Initialize detector67 print("Initializing YOLOv8n detector...")68 detector = YOLODetector("yolov8n.pt", 0.5)69 70 if detector.model is None:71 print("❌ Failed to load YOLO model")72 return False73 74 print("✅ YOLO model loaded successfully")75 76 # Test detection on dummy image77 print("Running detection on dummy image...")78 detections = detector.detect_objects(dummy_image)79 print(f"✅ Detection completed. Found {len(detections)} objects")80 81 # Test drawing detections82 if detections:83 annotated_image = detector.draw_detections(dummy_image, detections)84 print("✅ Detection drawing completed")85 86 # Test statistics87 stats = detector.get_detection_stats(detections)88 print(f"✅ Statistics generated: {stats}")89 90 return True91 92 except Exception as e:93 print(f"❌ Detector test failed: {e}")94 return False95 96def test_webcam_availability():97 """Test webcam availability."""98 print("\nTesting webcam availability...")99 100 try:101 from detection.webcam_capture import get_available_cameras, test_camera_availability102 103 available_cameras = get_available_cameras()104 print(f"Available cameras: {available_cameras}")105 106 if available_cameras:107 print("✅ At least one camera is available")108 109 # Test first available camera110 camera_index = available_cameras[0]111 if test_camera_availability(camera_index):112 print(f"✅ Camera {camera_index} is working")113 else:114 print(f"⚠️ Camera {camera_index} detected but not working properly")115 else:116 print("⚠️ No cameras detected (this is normal in some environments)")117 118 return True119 120 except Exception as e:121 print(f"❌ Webcam test failed: {e}")122 return False123 124def test_configuration():125 """Test configuration system."""126 print("\nTesting configuration...")127 128 try:129 from utils.config import app_config130 131 # Test configuration loading132 print(f"✅ Configuration loaded")133 print(f" - Default model: {app_config.detection.model_name}")134 print(f" - Confidence threshold: {app_config.detection.confidence_threshold}")135 print(f" - Available models: {len(app_config.available_models)}")136 137 # Test validation138 errors = app_config.validate_config()139 if not errors:140 print("✅ Configuration validation passed")141 else:142 print(f"⚠️ Configuration validation issues: {errors}")143 144 return True145 146 except Exception as e:147 print(f"❌ Configuration test failed: {e}")148 return False149 150def test_helpers():151 """Test helper functions."""152 print("\nTesting helper functions...")153 154 try:155 from utils.helpers import resize_image, calculate_iou, create_color_palette156 157 # Test image resizing158 dummy_image = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)159 resized = resize_image(dummy_image, 320, 240)160 print(f"✅ Image resize: {dummy_image.shape} -> {resized.shape}")161 162 # Test IoU calculation163 box1 = [10, 10, 50, 50]164 box2 = [30, 30, 70, 70]165 iou = calculate_iou(box1, box2)166 print(f"✅ IoU calculation: {iou:.3f}")167 168 # Test color palette169 colors = create_color_palette(10)170 print(f"✅ Color palette created: {len(colors)} colors")171 172 return True173 174 except Exception as e:175 print(f"❌ Helper functions test failed: {e}")176 return False177 178def main():179 """Run all tests."""180 print("🎯 YOLO Object Detection - Application Test Suite")181 print("=" * 50)182 183 tests = [184 ("Import Test", test_imports),185 ("Configuration Test", test_configuration),186 ("Helper Functions Test", test_helpers),187 ("Webcam Availability Test", test_webcam_availability),188 ("YOLO Detector Test", test_detector),189 ]190 191 passed = 0192 total = len(tests)193 194 for test_name, test_func in tests:195 print(f"\n📋 Running {test_name}...")196 try:197 if test_func():198 passed += 1199 print(f"✅ {test_name} PASSED")200 else:201 print(f"❌ {test_name} FAILED")202 except Exception as e:203 print(f"❌ {test_name} FAILED with exception: {e}")204 205 print("\n" + "=" * 50)206 print(f"📊 Test Results: {passed}/{total} tests passed")207 208 if passed == total:209 print("🎉 All tests passed! The application is ready to use.")210 print("\nTo run the application:")211 print(" streamlit run app.py")212 else:213 print("⚠️ Some tests failed. Please check the error messages above.")214 return 1215 216 return 0217 218if __name__ == "__main__":219 sys.exit(main())220 