from ultralytics import YOLO
import cv2
import winsound
import time
# Load pretrained YOLO model
model = YOLO("yolov8n.pt") # You can replace with yolov9 if needed
# Animal + Human classes we want to detect
TARGET_CLASSES = {
0: "person",
14: "bird",
15: "cat",
16: "dog",
17: "horse",
18: "sheep",
19: "cow",
20: "elephant",
21: "bear",
22: "zebra",
23: "giraffe"
}
# Alert sound file
ALERT_SOUND = "alert.wav"
def play_alert():
try:
winsound.PlaySound(ALERT_SOUND, winsound.SND_FILENAME)
except:
print("Error playing alert sound!")
def main():
cap = cv2.VideoCapture(0) # 0 = default webcam
last_alert_time = 0
while True:
ret, frame = cap.read()
if not ret:
break
results = model(frame)
detected = False
for r in results:
for box in r.boxes:
cls_id = int(box.cls)
conf = float(box.conf)
if cls_id in TARGET_CLASSES:
detected = True
x1, y1, x2, y2 = map(int, box.xyxy[0])
label = f"{TARGET_CLASSES[cls_id]} {conf:.2f}"
# Draw box
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(frame, label, (x1, y1 - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
# Play alert if detected someone/something
if detected and time.time() - last_alert_time > 2:
play_alert()
last_alert_time = time.time()
cv2.imshow("Animal + Human Detection", frame)
if cv2.waitKey(1) & 0xFF == 27: # ESC to exit
break
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
main()
Comments
Post a Comment