-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcamera.py
More file actions
64 lines (53 loc) · 2.13 KB
/
Copy pathcamera.py
File metadata and controls
64 lines (53 loc) · 2.13 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
import sys
sys.path.append("/usr/lib/python3/dist-packages") # Add system site packages
import cv2
import torch
import time
import numpy as np
from ultralytics import YOLO
from picamera2 import Picamera2
# ✅ Load YOLOv5 model (pretrained on COCO dataset)
model = YOLO("yolov5su.pt") # Small YOLOv5 model
# ✅ Open Raspberry Pi Camera
picam2 = Picamera2()
picam2.configure(picam2.create_preview_configuration(main={"format": "RGB888", "size": (640, 480)})) # ✅ Force RGB fo>picam2.start()
PHOTO_DELAY = 4 # Prevent duplicate photos for 10 seconds
last_photo_time = 0 # Timestamp for last saved image
print("✅ Camera started! Press 'q' to quit.")
while True:
print("test")
frame = picam2.capture_array() # ✅ Capture a frame in RGB format
print("test2")
if frame is None:
print("❌ Error: Failed to capture frame!")
break
# ✅ Ensure the image is in correct format for YOLO
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) # Convert from RGB to BGR for OpenCV
# ✅ Run YOLOv5 on the frame
results = model(frame, verbose=False)
detected = False
for result in results:
for box in result.boxes:
cls = int(box.cls) # Get class index
if cls == 0: # Class 0 is "person" in COCO dataset
detected = True
x1, y1, x2, y2 = map(int, box.xyxy[0])
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2) # Green box
cv2.putText(frame, "Human", (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# ✅ Save image if human is detected
if detected:
current_time = time.time()
if current_time - last_photo_time > PHOTO_DELAY:
last_photo_time = current_time
filename = f"human_detected_{int(time.time())}.jpg"
cv2.imwrite(filename, frame)
print(f"📸 Photo saved: {filename}")
# ✅ Show camera feed
#cv2.imshow("Raspberry Pi Camera - YOLOv5 Human Detection", frame)
print("test3")
# ✅ Exit if 'q' is pressed
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# ✅ Cleanup
picam2.stop()
cv2.destroyAllWindows()