OpenCV Python视频播放-如何为cv2.waitKey()设置正确的延迟 [英] OpenCV Python Video playback - How to set the right delay for cv2.waitKey()

查看:1267
本文介绍了OpenCV Python视频播放-如何为cv2.waitKey()设置正确的延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码捕获视频文件,将其翻转并保存.

I used the following code to capture a video file, flip it and save it.

#To save a Video File

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object
fourcc = cv2.cv.CV_FOURCC(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))

while(cap.isOpened()):
    ret, frame = cap.read()
    if ret==True:
        frame = cv2.flip(frame,0)

        # write the flipped frame
        out.write(frame)

        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()

该程序将输出另存为output.avi

This program saves the output as output.avi

现在,要播放视频文件,我使用了以下程序

Now, to playback the video file I used the following program

#Playing Video from File

import numpy as np
import cv2

cap = cv2.VideoCapture('output.avi')

print cap.get(5) #to display frame rate of video
#print cap.get(cv2.cv.CV_CAP_PROP_FPS)

while(cap.isOpened()): 
    ret, frame = cap.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #convert to grayscale

    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'): 
        break

cap.release()
cv2.destroyAllWindows()

此程序播放从第一个程序保存的视频文件output.avi.关键是,该视频显示快进.因此,我尝试更改cv2.waitKey()的延迟值.当我放100时,视频看起来不错.我如何知道该放哪个值?它应该与帧速率有关吗?我检查了output.avi的帧速率(请参见第二个程序中的cap.get(5)行),得到20.但是如果我将20用作cv2.waitKey()的延迟,则视频仍然太快.

This program plays the video file output.avi saved from the first program. The thing is, this video appears fast forward. So, I tried changing the delay value for cv2.waitKey(). The video looked fine when I put 100. How do I know which value to put there? Should it be related to the frame rate? I checked the frame rate of output.avi (see line cap.get(5) in second program) and got 20. But if I use 20 as delay for cv2.waitKey() the video is still too fast.

任何帮助将不胜感激.

推荐答案

来自

函数cv.waitKey([, delay])无限等待按键事件 (当delay <= 0时)或delay毫秒(当它为正时).

The function cv.waitKey([, delay]) waits for a key event infinitely (when delay <= 0) or for delay milliseconds, when it is positive.

如果FPS等于20,则在显示连续帧之间应该等待0.05秒.因此,只需将waitKey(50)放在imshow()之后,即可获得所需的播放速度.

If the FPS is equal to 20, then you should wait 0,05 seconds between displaying the consecutive frames. So just put waitKey(50) after imshow() in order to have the desired speed for the playback.

这篇关于OpenCV Python视频播放-如何为cv2.waitKey()设置正确的延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆