|
|
|
|
|
""" |
|
Created on Sun Aug 4 13:35:09 2024 |
|
|
|
@author: ysnrfd |
|
""" |
|
|
|
import cv2 |
|
from ultralytics import YOLO |
|
|
|
|
|
model = YOLO('yolov10n.pt') |
|
|
|
|
|
cap = cv2.VideoCapture(0) |
|
|
|
|
|
if not cap.isOpened(): |
|
print("Error: Could not open camera.") |
|
exit() |
|
|
|
|
|
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 512) |
|
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 512) |
|
|
|
while True: |
|
|
|
ret, frame = cap.read() |
|
if not ret: |
|
print("Error: Failed to capture image") |
|
break |
|
|
|
|
|
results = model(frame, imgsz=512, stream=True) |
|
|
|
|
|
for result in results: |
|
boxes = result.boxes.data.cpu().numpy() |
|
for box in boxes: |
|
x1, y1, x2, y2, score, class_id = map(int, box) |
|
label = f"{model.names[class_id]}: {score:.2f}" |
|
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 1) |
|
cv2.putText(frame, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1) |
|
|
|
|
|
cv2.imshow('YOLOv8n Real-Time Detection', frame) |
|
|
|
|
|
if cv2.waitKey(1) & 0xFF == ord('q'): |
|
break |
|
|
|
|
|
cap.release() |
|
cv2.destroyAllWindows() |
|
|