Skip to main content
 首页 » 编程设计

python之Kivy 相机内存错误

2025年02月15日15飞鱼

我在带有罗技网络摄像头的 Raspberry Pi 3 上运行的 kivy 中有以下摄像头代码:

class KivyCamera(Image): 
 
    def __init__(self, **kwargs): 
        super(KivyCamera, self).__init__(**kwargs) 
        self.capture = None 
 
    def start(self, capture, fps=30): 
        self.capture = capture 
        Clock.schedule_interval(self.update, 1.0 / fps) 
 
    def stop(self): 
        Clock.unschedule_interval(self.update) 
        self.capture = None 
 
    def update(self, dt): 
        ret, frame = self.capture.read() 
        if ret: 
            # convert it to texture 
            cv2.putText(frame, "Testing!", (0, 50), cv2.FONT_HERSHEY_COMPLEX, 2, (100, 0, 255)) 
            buf1 = cv2.flip(frame, 0) 
 
            if (recON == 1): 
                out.write(frame) 
            # 
            buf = buf1.tostring() 
            image_texture = Texture.create( 
                #size=(frame.shape[1], frame.shape[0]), colorfmt='bgr') 
                size=(frame.shape[1], frame.shape[0]), colorfmt='rgb') 
            image_texture.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte') 
            #self.canvas.ask_update() 
            self.texture = image_texture 

从 Logitech C920(在 LCD 上)显示帧大约 3 分钟后,我得到下面的内存异常。如果我使用 Logitech C170,它将运行更长时间约 5 分钟:

对我来说,缓冲区似乎溢出了。 C920 具有更高分辨率,填充速度更快,但我在代码中看不到缓冲区在哪里填充?

请您参考如下方法:

运行代码时我注意到这个警告:

当我更改 python 行时:

image_texture.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte') 

到:

image_texture.blit_buffer(buf, colorfmt='rgb', bufferfmt='ubyte') 

我不再收到警告 或内存泄漏。我使用 opencv

的 cvtColor 特性交换了颜色空间