python 在OpenCV中更改FPS

tf7tbtn2  于 2023-01-24  发布在  Python
关注(0)|答案(2)|浏览(300)

我有一个技术应用程序,需要每秒捕捉几帧。在下面的代码中设置视频写入器为3帧每秒的结果在网络摄像头的正常帧速率约30帧被保存。什么是选项保存录制的3帧每秒,并让其他27帧左右去?提前感谢。

import cv2
import numpy as np
import time
import datetime
import pathlib
import imutils

cap = cv2.VideoCapture(0)

if (cap.isOpened() == False): 
  print("Unable to read camera feed")

capture_duration = 15
frame_per_sec = 3
frame_width = 80
frame_height = 60

out = cv2.VideoWriter('C:\\Users\\student\\Desktop\\videoFile.avi',cv2.VideoWriter_fourcc('m','j','p','g'),frame_per_sec, (frame_width,frame_height))

start_time = time.time()
while( int(time.time() - start_time) < capture_duration ):
    ret, frame = cap.read()
    if ret==True:
        frame = imutils.resize(frame, width=frame_width)
        out.write(frame)
        cv2.imshow('frame',frame) 
        if cv2.waitKey(1) & 0xFF == ord('q'):
          break
    else:
        break

cap.release()
out.release()
 
cv2.destroyAllWindows()
zzwlnbp8

zzwlnbp81#

您可以通过VideoWriter设置输出的FPS,
但您没有尝试通过VideoCapture设置输入的FPS。
为此,您可以尝试在创建cap之后使用cv2.CAP_PROP_FPS属性调用cv2.VideoCapture
例如:

cap.set(cv2.CAP_PROP_FPS, 3)
    • 但是**-注意实际的行为取决于你使用的特定的捕获设备。有些只支持某些FPSs。也可以参考这篇文章:change frame rate in opencv 3.4.2.

如果它确实起作用了,你将能够大大简化你的代码--只需捕捉帧,处理它们并保存(不需要任何手动的fps管理)。

2izufjch

2izufjch2#

此方法以编程方式设置每秒帧数。当帧速率设置为30fps时,将创建一个6.1mb的文件,当设置为3fps时,将创建一个0.9mb的文件。

#!/usr/bin/env python3

import cv2
import numpy as np
import time
import datetime
import pathlib
import imutils

cap = cv2.VideoCapture(0)

if (cap.isOpened() == False): 
  print("Unable to read camera feed")

capture_duration = 15
frame_per_sec = 30
prev = 0
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))

out = cv2.VideoWriter('C:\\videoPy\\LZ\\'outpout.avi',cv2.VideoWriter_fourcc('m','j','p','g'),frame_per_sec, (frame_width,frame_height))

start_time = time.time()
while( int(time.time() - start_time) < capture_duration ): 
#start fps
  time_elapsed = time.time() - prev
  while(time_elapsed > 1./frame_per_sec):                   
        ret, frame = cap.read()
        if not ret:
            break
        if time_elapsed > 1./frame_per_sec:
          prev = time.time()
#end fps
        if ret==True:
          frame = imutils.resize(frame, width=frame_width)
          out.write(frame)
          cv2.imshow('frame',frame) 
        if cv2.waitKey(1) & 0xFF == ord('q'):
          break
        else:
           break

cap.release()
out.release()
 
cv2.destroyAllWindows()

相关问题