opencv - 视频中的帧速率不正确

标签 opencv frame-rate

我有一个 25 fps 的 12 秒视频。当我在 opencv 中以 25 fps 播放视频时,视频变为 16 秒。我通过使用获得 fps fps = get(cv2.CAP_PROP_FPS) 然后我设置 waitKey(1000/fps) 但视频播放速度很慢...

import numpy as np
import cv2
import time
start = time.time()

cap = cv2.VideoCapture("hackerman.mp4")
fps = cap.get(cv2.CAP_PROP_FPS)
print(fps)
while True:
    # Capture frame-by-frame
    ret, frame = cap.read()
    if ret == True:
        frame_new = frame
    else:
        end = time.time()
    # frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # turn video gray

    # Display the resulting frame
    cv2.namedWindow('frame', cv2.WINDOW_NORMAL)
    cv2.imshow('frame', frame_new)

    k = cv2.waitKey(int(round(1000/fps))) & 0xFF
    if k == 27:         # wait for ESC key to exit
        break
    elif cv2.getWindowProperty("frame", 0) == -1:
        break


print(end-start)
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

最佳答案

看来 cap.read() 的读取速度比帧速率更快,如果您正在处理帧而不是显示它们,这将是非常理想的 - 因此在您的应用程序中,您需要使用例如添加延迟time.sleep() 或在您的情况下 waitKey() ,并且必须计算该值才能达到 25fps 的帧速率。

对于最精确的 25fps,将下一帧的结束时间基于总体开始时间,如下所示(未经测试):

frameref_ms = int(time.time()*1000)
frametime_ms = int(1000/fps)

while True:
    # update frameref to end frame period from now (regardless of how long reading and displaying the frame takes)
    frameref_ms += frametime_ms
    # Capture frame-by-frame
    ret, frame = cap.read()
    if ret == True:
        frame_new = frame
    else:
        end = time.time()
    # frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # turn video gray

    # Display the resulting frame
    cv2.namedWindow('frame', cv2.WINDOW_NORMAL)
    cv2.imshow('frame', frame_new)
    # wait for a keypress or the time needed to finish the frame duration
    k = cv2.waitKey(frameref_ms-int(time.time()*1000)) & 0xFF
    if k == 27:         # wait for ESC key to exit
        break
    elif cv2.getWindowProperty("frame", 0) == -1:
        break

这种拥有完成显示/读取下一帧的绝对时间的技术意味着帧速率将是准确的,只要其他任务不占用太多 CPU,就会自动补偿多任务其他操作系统任务你的代码几乎无法运行,如果你遇到这个问题,我想你将不得不提高Python的优先级,这会减慢其他程序的速度。我已经在温度/振动测量的定时采样中使用了这种方法,并且效果非常好。请参阅我的答案之一 Inaccurate while loop timing in Python 中的相同技术

如果您非常小心/悲观,您还应检查在帧读取+显示时间长于帧周期的情况下,waitKey() 是否没有给出负延迟.

关于opencv - 视频中的帧速率不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55953489/

相关文章:

.net - 在 WPF .Net 中测量 UI 性能的正确方法

javascript - 如何判断 HTML5 Canvas 性能缓慢的原因?

c++ - 区分实线和虚线的相关性

c++ - OpenCV 将加载图像但不显示它

python - 图像分割中的轮廓补全

c++ - 计算的 fps 如何大于相机声明的 fps?

opencv - 在 OpenCV 图像拼接中混合伪影

visual-c++ - Opencv中的相关函数

c++ - 调节后检索/调试当前 FPS?

c++ - openGL 每秒平均帧数是多少