使用OpenCv和PiCamera(python)的低FPS

2024-04-27 23:10:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将我的OpenCV程序与我的Raspberry Pi PiCamera接口。每次我使用OpenCV捕捉视频时,它都会大幅降低FPS。当我使用PiCamera的库拍摄视频时,一切都很顺利

  1. 为什么会这样
  2. 有办法解决吗

这是我的代码:

import time
import RPi.GPIO as GPIO
from PCA9685 import PCA9685
import numpy as np
import cv2

try:


    cap = cv2.VideoCapture(0)
    cap.set(cv2.CAP_PROP_FPS, 90)
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, 800)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 700)

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

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

# When everything is done, release the capture


except:
    pwm.exit_PCA9685()
    print ("\nProgram end")
    exit()
cap.release()
cv2.destroyAllWindows()

这就是我遇到的错误:

enter image description here


Tags: import视频gpioascv2frameopencvcap
1条回答
网友
1楼 · 发布于 2024-04-27 23:10:57
  1. 首先,这些是警告而不是错误

  2. 减少视频维度。指定尺寸标注

  3. cv2.VideoCapture有一些问题,因为它会缓冲帧,并且帧会排队,因此如果您正在进行一些处理,并且速度小于VideoCapture的带宽,视频会变慢

因此,这里是一个无缓冲区的VideoCapture

视频捕获\u Q\u buf.py

import cv2, queue as Queue, threading, time


is_frame = True
# bufferless VideoCapture


class VideoCaptureQ:

    def __init__(self, name):
        self.cap = cv2.VideoCapture(name)
        self.q = Queue.Queue()
        t = threading.Thread(target=self._reader)
        t.daemon = True
        t.start()

    # read frames as soon as they are available, keeping only most recent one
    def _reader(self):
        while True:
            ret, frame = self.cap.read()
            if not ret:
                global is_frame
                is_frame = False
                break
            if not self.q.empty():
                try:
                    self.q.get_nowait()   # discard previous (unprocessed) frame
                except Queue.Empty:
                    pass
            self.q.put(frame)

    def read(self):
        return self.q.get()

使用它:

test.py

import video_capture_Q_buf as vid_cap_q # import as alias
from video_capture_Q_buf import VideoCaptureQ # class import
import time

cap = VideoCaptureQ(vid_path)

while True:

    t1 = time.time()

    if vid_cap_q.is_frame == False:
        print('no more frames left')
        break

    try:
        ori_frame = cap.read()
        # do your stuff
    except Exception as e:
        print(e)
        break
    t2 = time.time()
    print(f'FPS: {1/(t2-t1)}')

相关问题 更多 >