获取视频帧.py 1021 B

123456789101112131415161718192021222324252627282930313233343536
  1. import cv2
  2. def get_frame_at_time(video_path, time_ms, output_image_path):
  3. """
  4. 获取视频指定毫秒数的帧
  5. :param video_path: 视频文件路径
  6. :param time_ms: 需要获取的时间点,单位为毫秒
  7. :param output_image_path: 保存帧的路径
  8. """
  9. cap = cv2.VideoCapture(video_path)
  10. # 设置视频的位置到指定的毫秒数 [5]
  11. cap.set(cv2.CAP_PROP_POS_MSEC, time_ms)
  12. # 读取帧 [2]
  13. ret, frame = cap.read()
  14. if ret:
  15. # 保存图像
  16. cv2.imwrite(output_image_path, frame)
  17. print(f"Frame at {time_ms}ms saved to {output_image_path}")
  18. else:
  19. print("Failed to read frame")
  20. cap.release()
  21. if __name__ == '__main__':
  22. video_path = r"C:\Code\ML\Video\直播数据\video\vortexcards.mp4"
  23. hours = 1
  24. minutes = 53
  25. seconds = 22
  26. time_in_ms = (hours * 3600 + minutes * 60 + seconds) * 1000
  27. # 示例:获取视频的第 5000 毫秒(5秒)的帧
  28. get_frame_at_time(video_path, time_in_ms, "frame.jpg")