import cv2 import torch import numpy as np Load YOLOv5 model model =…
- User
import cv2 import torch import numpy as np
Load YOLOv5 model
model = torch.hub.load('ultralytics/yolov5', 'yolov5n6')
Your supervision library would be used here
import supervision as sv
Initialize the camera (0 for default camera, 1 for external cameras, and so on)
camera = cv2.VideoCapture(0)
Define the BoxAnnotator from the supervision library
box_annotator = sv.BoxAnnotator(thickness=4, text_thickness=4, text_scale=2)
def live_inference(camera): while True: # Capture frame-by-frame from camera ret, frame = camera.read() if not ret: print("Failed to grab frame") break
code# Convert the image from BGR to RGB frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Perform inference results = model(frame_rgb, size=700) detections = sv.Detections.from_yolov5(results) detections = detections[(detections.class_id == 0) & (detections.confidence > 0.5)] # Annotate frame_annotated = box_annotator.annotate(scene=frame_rgb, detections=detections) # Convert the image from RGB to BGR for OpenCV display frame_annotated_bgr = cv2.cvtColor(frame_annotated, cv2.COLOR_RGB2BGR) # Display the resulting frame cv2.imshow('YOLOv5 Live Detection', frame_annotated_bgr) # Break the loop if ‘q’ is pressed if cv2.waitKey(1) & 0xFF == ord('q'): break # When everything done, release the capture camera.release() cv2.destroyAllWindows()Run the live inference function
live_inference(camera)
add something so that it displays the dimensions of the frame when running
- Assistant