大家好,我尝试获取视频中每次检测的时间戳,我尝试了此操作,但得到了一个空列表
from ultralytics import YOLO
from datetime import timedelta
import cv2
model = YOLO('path/yolov8n-cls.pt')
video_path='your video path'
cap=cv2.VideoCapture(video_path)
results = model.predict(video_path) # results list for each frame
for i, frame_result in enumerate(results.xyxy[0]): # xyxy format contains bounding box coordinates and class probabilities
timestamp = timedelta(seconds=i /cap.get(cv2.CAP_PROP_FPS)) # calculate timestamp
print(f"Timestamp: {timestamp}, Probs: {frame_result['probs']}")
我尝试设置 Save=true 但什么也没发生
使用边界框的结果使我能够了解何时做出预测。此代码只是将帧和时间戳(以秒为单位)存储到名为“Detected_timestamps”的列表中。时间戳以毫秒为单位。
注意:这会对视频的每一帧运行检测。
import cv2
import time
from datetime import timedelta
from ultralytics import YOLO
# Load the YOLOv8 model
model = YOLO(r'best.pt')
# Open the video file
video_path = r"vid-short.mp4"
cap = cv2.VideoCapture(video_path)
detected_timestamps = []
frame_no = 0
# Loop through the video frames
while cap.isOpened():
# Read a frame from the video
success, frame = cap.read()
if success:
# Run YOLOv8 inference on the frame
results = model.predict(frame)
# Visualize the results on the frame
annotated_frame = results[0].plot()
# Get the box detection tensor
if len(results[0].boxes.cls) > 0:
# Get current timestamp
message = "for frame : " + str(frame_no) + " timestamp is: ", str(cap.get(cv2.CAP_PROP_POS_MSEC))
print(message)
detected_timestamps.append(message)
frame_no += 1
# 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
# Release the video capture object and close the display window
cap.release()
cv2.destroyAllWindows()
print(detected_timestamps)