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

Get current video playing position using cv2 in Python

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

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

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()

有没有办法获取或计算这个值,它必须代表请求时间播放的位置(时间上,即 24.000 秒视频的 12.500 秒)。

谢谢!

是的,这可以通过使用 VideoCapture.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()