简体   繁体   English

Python/OpenCV - 错误的实际相机 FPS 或太慢的例程

[英]Python/OpenCV - Wrong actual camera FPS or too slow routine

I'm using python and OpenCV to acquire video from the webcam.我正在使用 python 和 OpenCV 从网络摄像头获取视频。 So as to record the video, I need the FPS information.为了录制视频,我需要 FPS 信息。 From get property of cv.VideoCapture I get 30fps:cv.VideoCaptureget属性中,我得到 30fps:

fps = cap.get(cv.CAP_PROP_FPS)

However, when I build the thread that reads the subsequent frames, the actual framerate seems to be much lower (~12):但是,当我构建读取后续帧的线程时,实际帧速率似乎要低得多(~12):

def run(self) -> None:
    log(f'Started frame grabber with FPS = {self.fps}')
    while self.keep_grabbing:
        _now = time.perf_counter()
        # frame = self.cap.grab()    # SAME RESULT AS WITH read()
        ret, frame = self.cap.read()   
        now = time.perf_counter()
        log(f'Elapsed Time: {now - _now}')

The result is an average 0.083s elapsed (about 12fps) I can't understand if I'm getting a slow software (but I cannot figure out what to change), or if the get property is returning a wrong FPS.结果是平均经过 0.083 秒(大约 12 fps) 我不明白我是否正在获得一个缓慢的软件(但我无法弄清楚要更改什么),或者 get 属性是否返回了错误的 FPS。 Any suggestion?有什么建议吗?

The problem was the ApiPreference with which the camera was opened.问题是打开相机的ApiPreference By default the cv.CAP_ANY was used that implied the behavior described by the question.默认情况下,使用cv.CAP_ANY暗示问题描述的行为。 It seems that the auto-detection of the API does not work effectively API 的自动检测似乎无法有效工作

In particular, for the PC's webcam under Ubuntu 20.04, the parameter cv.CAP_V4L makes the camera work with an effective FPS of 29.8, very near to the theoretical one (30).特别是对于 Ubuntu 20.04 下的 PC 网络摄像头,参数cv.CAP_V4L使摄像头以 29.8 的有效 FPS 工作,非常接近理论值 (30)。

The code becomes:代码变为:

import cv2 as cv
import time

# Here the ApiPreference must be chosen carefully
cap = cv.VideoCapture(0, cv.CAP_V4L)

if not cap.isOpened():
    exit('Camera not opened')

while True:
    _now = time.perf_counter()
    ret, frame = cap.read()
    now = time.perf_counter()
    print(f'Elapsed Time: {now - _now}')
    if not ret:
        exit('Frame not grabbed')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM