-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdetect_image.py
More file actions
78 lines (63 loc) · 2.43 KB
/
Copy pathdetect_image.py
File metadata and controls
78 lines (63 loc) · 2.43 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
from ultralytics import YOLO
import cv2
import argparse
def detect_image(model, image_path):
results = model(image_path)
result = results[0]
img = result.orig_img.copy()
for box in result.boxes:
x1, y1, x2, y2 = box.xyxy[0].cpu().numpy().astype(int)
cls_id = int(box.cls[0])
label = model.names[cls_id]
conf = float(box.conf[0])
cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(img, f"{label} {conf:.2f}", (x1, y1 - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
cv2.imshow("YOLOv8 Image Detection", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
def detect_video(model, video_path):
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
print("Error: Could not open video.")
return
# ✅ Get FPS of the video and calculate correct delay
fps = cap.get(cv2.CAP_PROP_FPS)
if fps == 0: # fallback if FPS not available
fps = 60
delay = int(1000 / fps)
while True:
ret, frame = cap.read()
if not ret:
break
results = model(frame, verbose=False)
for result in results:
for box in result.boxes:
x1, y1, x2, y2 = box.xyxy[0].cpu().numpy().astype(int)
cls_id = int(box.cls[0])
label = model.names[cls_id]
conf = float(box.conf[0])
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(frame, f"{label} {conf:.2f}", (x1, y1 - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
cv2.imshow("YOLOv8 Video Detection", frame)
if cv2.waitKey(delay) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--image", type=str, help="Path to image file")
parser.add_argument("--video", type=str, help="Path to video file (or 0 for webcam)")
args = parser.parse_args()
# model = YOLO("yolov8m.pt") # or yolov8l.pt
model = YOLO("yolov8n.pt") # Nano version, much faster
if args.image:
detect_image(model, args.image)
elif args.video:
if args.video == "0":
detect_video(model, 0) # webcam
else:
detect_video(model, args.video)
else:
print("Please provide either --image <path> or --video <path/0>")