在Python中使用cv2获取当前视频播放位置



我正试图从使用Python的CV2播放视频中获得当前播放时间位置(如果可能的话以毫秒为单位)。

目前我正在使用这个示例代码来播放视频文件

import cv2
import numpy as np
file_name = "2.mp4"
window_name = "window"
interframe_wait_ms = 30
cap = cv2.VideoCapture(file_name)
if not cap.isOpened():
print("Error: Could not open video.")
exit()
cv2.namedWindow(window_name, cv2.WND_PROP_FULLSCREEN)
cv2.setWindowProperty(window_name, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
while (True):
ret, frame = cap.read()
if not ret:
print("Reached end of video, exiting.")
break
cv2.imshow(window_name, frame)
if cv2.waitKey(interframe_wait_ms) & 0x7F == ord('q'):
print("Exit requested.")
break
cap.release()
cv2.destroyAllWindows()

是否有一种方法来获得这个值或计算它,它必须表示在请求时播放的位置(在时间上,即24000秒视频的12.500秒)。

谢谢!

是的,这可以通过使用videoccapture .get(cv2.CAP_PROP_FPS)查询视频FPS并跟踪帧索引来实现。

的例子:

file_name = "2.mp4"
window_name = "window"
interframe_wait_ms = 30
cap = cv2.VideoCapture(file_name)
if not cap.isOpened():
print("Error: Could not open video.")
exit()
fps = cap.get(cv2.CAP_PROP_FPS)
cv2.namedWindow(window_name, cv2.WND_PROP_FULLSCREEN)
cv2.setWindowProperty(window_name, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
frame_index = 0
while True:
ret, frame = cap.read()
if not ret:
print("Reached end of video, exiting.")
break
cv2.imshow(window_name, frame)
print(F"playback time: {(frame_index/fps)*1000}ms")
if cv2.waitKey(interframe_wait_ms) & 0x7F == ord('q'):
print("Exit requested.")
break
frame_index += 1
cap.release()
cv2.destroyAllWindows()

相关内容

  • 没有找到相关文章

最新更新