snipplets.dev/projects/CV/Stream/__main__.py

51 lines
1.2 KiB
Python
Raw Normal View History

2023-09-29 21:51:53 +03:00
import cv2
from ultralytics import YOLO
# https://docs.ultralytics.com/modes/predict/#streaming-source-for-loop
# Load the YOLOv8 model
model = YOLO('yolov8m.pt')
# Open the video file
video_path = 'run.mp4'
cap = cv2.VideoCapture(video_path)
2023-10-03 21:56:17 +03:00
fps = 0
prev_frame_time = 0
new_frame_time = 0
2023-09-29 21:51:53 +03:00
# Loop through the video frames
while cap.isOpened():
# Read a frame from the video
success, frame = cap.read()
2023-10-03 21:56:17 +03:00
# Set current frame time
new_frame_time = time.time()
2023-09-29 21:51:53 +03:00
if success:
# Run YOLOv8 inference on the frame
results = model(frame)
# Visualize the results on the frame
annotated_frame = results[0].plot()
2023-10-03 21:56:17 +03:00
# Calculate FPS
fps = int(1 / (new_frame_time - prev_frame_time))
prev_frame_time = new_frame_time
2023-09-29 21:51:53 +03:00
# Display the annotated frame
cv2.imshow('YOLOv8 Inference', annotated_frame)
# Break the loop if 'q' is pressed
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
# Break the loop if the end of the video is reached
break
2023-10-03 21:56:17 +03:00
print(fps)
2023-09-29 21:51:53 +03:00
# Release the video capture object and close the display window
cap.release()
cv2.destroyAllWindows()