Yolo Detect
Yolo Detect
import sys
import argparse
import glob
import time
import cv2
import numpy as np
from ultralytics import YOLO
parser = argparse.ArgumentParser()
parser.add_argument('--model', help='Path to YOLO model file (example:
"runs/detect/train/weights/best.pt")',
required=True)
parser.add_argument('--source', help='Image source, can be image file ("test.jpg"),
\
image folder ("test_dir"), video file ("testvid.mp4"), or index
of USB camera ("usb0")',
required=True)
parser.add_argument('--thresh', help='Minimum confidence threshold for displaying
detected objects (example: "0.4")',
default=0.5)
parser.add_argument('--resolution', help='Resolution in WxH to display inference
results at (example: "640x480"), \
otherwise, match source resolution',
default=None)
parser.add_argument('--record', help='Record results from video or webcam and save
it as "demo1.avi". Must specify --resolution argument to record.',
action='store_true')
args = parser.parse_args()
# Parse input to determine if image source is a file, folder, video, or USB camera
img_ext_list = ['.jpg','.JPG','.jpeg','.JPEG','.png','.PNG','.bmp','.BMP']
vid_ext_list = ['.avi','.mov','.mp4','.mkv','.wmv']
if os.path.isdir(img_source):
source_type = 'folder'
elif os.path.isfile(img_source):
_, ext = os.path.splitext(img_source)
if ext in img_ext_list:
source_type = 'image'
elif ext in vid_ext_list:
source_type = 'video'
else:
print(f'File extension {ext} is not supported.')
sys.exit(0)
elif 'usb' in img_source:
source_type = 'usb'
usb_idx = int(img_source[3:])
elif 'picamera' in img_source:
source_type = 'picamera'
picam_idx = int(img_source[8:])
else:
print(f'Input {img_source} is invalid. Please try again.')
sys.exit(0)
# Set up recording
record_name = 'demo1.avi'
record_fps = 30
recorder = cv2.VideoWriter(record_name, cv2.VideoWriter_fourcc(*'MJPG'),
record_fps, (resW,resH))
t_start = time.perf_counter()
elif source_type == 'video': # If source is a video, load next frame from video
file
ret, frame = cap.read()
if not ret:
print('Reached end of the video file. Exiting program.')
break
elif source_type == 'usb': # If source is a USB camera, grab frame from camera
ret, frame = cap.read()
if (frame is None) or (not ret):
print('Unable to read frames from the camera. This indicates the camera
is disconnected or not working. Exiting program.')
break
# Extract results
detections = results[0].boxes
# Go through each detection and get bbox coords, confidence, and class
for i in range(len(detections)):
# Calculate and draw framerate (if using video, USB, or Picamera source)
if source_type == 'video' or source_type == 'usb' or source_type == 'picamera':
cv2.putText(frame, f'FPS: {avg_frame_rate:0.2f}', (10,20),
cv2.FONT_HERSHEY_SIMPLEX, .7, (0,255,255), 2) # Draw framerate
# Append FPS result to frame_rate_buffer (for finding average FPS over multiple
frames)
if len(frame_rate_buffer) >= fps_avg_len:
temp = frame_rate_buffer.pop(0)
frame_rate_buffer.append(frame_rate_calc)
else:
frame_rate_buffer.append(frame_rate_calc)
# Clean up
print(f'Average pipeline FPS: {avg_frame_rate:.2f}')
if source_type == 'video' or source_type == 'usb':
cap.release()
elif source_type == 'picamera':
cap.stop()
if record: recorder.release()
cv2.destroyAllWindows()