-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfinal_1.py
More file actions
101 lines (80 loc) · 2.45 KB
/
final_1.py
File metadata and controls
101 lines (80 loc) · 2.45 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
import cv2
import argparse
from ultralytics import YOLO
import supervision as sv
import numpy as np
from pydub import AudioSegment
from pydub.playback import play
import threading
import pygame
MOTORCYCLE_SOUND_FILE="D:\hackathon\Bird detection\motorcycle_sound.wav"
pygame.mixer.init()
motorcycle_sound = pygame.mixer.Sound(MOTORCYCLE_SOUND_FILE)
ZONE_POLYGON = np.array([
[0, 0],
[1, 0],
[1, 1],
[0, 1]
])
def parse_arguments() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="YOLOv8 live")
parser.add_argument(
"--webcam-resolution",
default=[1280, 720],
nargs=2,
type=int
)
args = parser.parse_args()
return args
def main():
args = parse_arguments()
frame_width, frame_height = args.webcam_resolution
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, frame_width)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, frame_height)
model = YOLO("yolov8n.pt")
box_annotator = sv.BoxAnnotator(
thickness=2,
text_thickness=2,
text_scale=1
)
zone_polygon = (ZONE_POLYGON * np.array(args.webcam_resolution)).astype(int)
zone = sv.PolygonZone(polygon=zone_polygon, frame_resolution_wh=tuple(args.webcam_resolution))
zone_annotator = sv.PolygonZoneAnnotator(
zone=zone,
color=sv.Color.red(),
thickness=2,
text_thickness=4,
text_scale=2
)
sound_playing = False
while True:
ret, frame = cap.read()
result = model(frame, agnostic_nms=True)[0]
detections = sv.Detections.from_yolov8(result)
detections = detections[detections.class_id == 14]
labels = [
f"{model.model.names[class_id]} {confidence:0.2f}"
for _, confidence, class_id, _
in detections
]
frame = box_annotator.annotate(
scene=frame,
detections=detections,
labels=labels
)
zone.trigger(detections=detections)
frame = zone_annotator.annotate(scene=frame)
if len(detections) > 0:
if not sound_playing:
motorcycle_sound.play(-1) # Play sound in a loop
sound_playing = True
else:
if sound_playing:
motorcycle_sound.stop()
sound_playing = False
cv2.imshow("yolov8", frame)
if (cv2.waitKey(30) == 27):
break
if __name__ == "__main__":
main()