i have an object detection code:"import cv2 import torch import numpy as np Load YOLOv5…
- User
i have an object detection code:"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
# 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) "
remember the size is size=700
help me implement a region of interest polygon where the detection only runs inside the dedicated ROI?
- Assistant
- User
thanks! now how can i implement a display number of detected within the region?
- Assistant
- User
what changes did you make so that i will only copy those
- Assistant
To add the functionality to display the number of detected objects within the region of interest (ROI), the primary additions are the following lines of code:
- After filtering the detections:
# Get the number of detections within the ROI num_detections = len(detections)- Using
cv2.putTextto draw the count on the annotated frame:
# Display the number of detected objects on the frame text = f"Detections in ROI: {num_detections}" cv2.putText(frame_annotated, text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2, cv2.LINE_AA)Insert these changes right after the detections are annotated on the original frame. Here's the updated section of the code where you'll add these lines: