|
| 1 | +import torch |
| 2 | +import cv2 |
| 3 | +import warnings |
| 4 | +import os |
| 5 | +from ultralytics import YOLO |
| 6 | +import pygame |
| 7 | + |
| 8 | +# Suppress the wayland warning |
| 9 | +os.environ["QT_QPA_PLATFORM"] = "xcb" # Set to "wayland" if needed |
| 10 | + |
| 11 | +# Suppress Qt font warnings |
| 12 | +warnings.filterwarnings("ignore", message="QFont::fromString") |
| 13 | +# Suppress PyTorch FutureWarnings |
| 14 | +warnings.filterwarnings("ignore", category=FutureWarning) |
| 15 | + |
| 16 | +# Enable CPU |
| 17 | +device = 'cpu' |
| 18 | +model = YOLO("yolo11s.pt").to(device) |
| 19 | + |
| 20 | +# Open video file or webcam |
| 21 | +cap = cv2.VideoCapture(0) # Replace 0 with file path for a video |
| 22 | + |
| 23 | +pygame.mixer.init() |
| 24 | +alarm_sound = pygame.mixer.Sound('alarm.mp3') |
| 25 | + |
| 26 | +alerted = False |
| 27 | + |
| 28 | +while True: |
| 29 | + ret, frame = cap.read() |
| 30 | + if not ret: |
| 31 | + break |
| 32 | + |
| 33 | + # Resize frame to smaller size for CPU |
| 34 | + #frame = cv2.resize(frame, (1024, 1024)) |
| 35 | + |
| 36 | + # Convert image to RGB and to appropriate device and precision |
| 37 | + img_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) |
| 38 | + img_rgb = torch.from_numpy(img_rgb).permute(2, 0, 1).unsqueeze(0).to(device) |
| 39 | + img_rgb = img_rgb.float() # Convert to floating point |
| 40 | + img_rgb = img_rgb / 255.0 # Normalize tensor to [0.0, 1.0] |
| 41 | + |
| 42 | + # Run YOLOv9 inference |
| 43 | + with torch.no_grad(): |
| 44 | + results = model(img_rgb) |
| 45 | + |
| 46 | + # Check for human detection and play sound once |
| 47 | + if 0 in results[0].boxes.cls: |
| 48 | + if not alerted: |
| 49 | + alarm_sound.play() |
| 50 | + alerted = True |
| 51 | + else: |
| 52 | + alerted = False |
| 53 | + |
| 54 | + # Convert the results back to BGR format for OpenCV |
| 55 | + result_img = cv2.cvtColor(results[0].plot(), cv2.COLOR_RGB2BGR) |
| 56 | + |
| 57 | + # Scale the result image for display |
| 58 | + result_img = cv2.resize(result_img, (1280, 860)) # Adjust dimensions as needed |
| 59 | + |
| 60 | + # Display the output frame |
| 61 | + cv2.imshow('Uykum geldi', result_img) |
| 62 | + |
| 63 | + # Exit loop on 'q' press |
| 64 | + if cv2.waitKey(1) & 0xFF == ord('q'): |
| 65 | + break |
| 66 | + |
| 67 | +# Release video capture and close windows |
| 68 | +cap.release() |
| 69 | +cv2.destroyAllWindows() |
0 commit comments