我试着从picamera得到2帧。为什么它工作得很慢?

2024-06-01 02:02:37 发布

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

picamera.PiCamera()线程中,我尝试获得用于opencv处理的cls.frameCV2 = snap.array,以及另一个用于web流的{}。两种方法都有效,但速度很慢。在

有什么问题吗?如果只使用frameCV2它工作得相当快,或者如果我只使用stream.read,它也可以。在

下面是我的代码片段:

import time
import io
import threading
import cv2
import picamera
from picamera.array import PiRGBArray

class Camera(object):
    thread = None  # background thread that reads frames from camera
    frame = None  # current frame is stored here by background thread
    frameCV2 = None # same, but as a numpy array
    last_access = 0  # time of last client access to the camera

    def initialize(self):
        if Camera.thread is None:
            # start background frame thread
            Camera.thread = threading.Thread(target=self._thread)
            Camera.thread.start()

            # wait until frames start to be available
            while self.frame is None:
                time.sleep(0)

    def get_frame(self):
        Camera.last_access = time.time()
        self.initialize()
        return self.frame

    def get_frame_for_internal_proc(self): # store frame for cv2 я добавил
        Camera.last_access = time.time()
        self.initialize()
        return self.frameCV2

    @classmethod
    def _thread(cls):
        with picamera.PiCamera() as camera:
            # camera setup
            camera.resolution = (800, 600)
            camera.hflip = True
            camera.vflip = True

            # let camera warm up
            camera.start_preview()
            time.sleep(2)

            rawCapture = PiRGBArray(camera) # я добавил

            stream = io.BytesIO()
            for snap in camera.capture_continuous(rawCapture, 'bgr',
                                                 use_video_port=True):
                cls.frameCV2 = snap.array # frame for cv2

                # store frame for web
                camera.capture(stream, format='jpeg')
                stream.seek(0)
                cls.frame = stream.read()

                # reset stream for next frame
                stream.seek(0)
                stream.truncate()

                rawCapture.truncate(0)

                # if there hasn't been any clients asking for frames in
                # the last 10 seconds stop the thread
                if time.time() - cls.last_access > 10:
                    break
        cls.thread = None

Tags: importselfnoneforstreamaccesstimethread
1条回答
网友
1楼 · 发布于 2024-06-01 02:02:37

所以,我没有找到让它更快工作的方法。低速的主要原因是在camera.capture_continuous圆内捕获了两倍。在

总之,我解决了这个问题,使用了一个线程来处理frame和{},只需将第二代转换为第一代。我只是把self.frame = cv2.imencode('.jpg', self.frameCV2)[1].tobytes()放到get_frame()方法中,该方法将numpy矩阵转换为格式,适合web流媒体。在

现在效果很好。在

相关问题 更多 >