2

基于 arnav 的示例,我正在尝试将此自定义相机小部件添加到 kv 结构中。不幸的是,我仍然不清楚这种“机制”。所以我最终得到了以下代码。单击开始按钮后,凸轮的灯被激活。但是没有显示“视频流”。当仅使用 cv2.VideoCapture(0) 运行 arnav 的代码时,会显示“视频流”。

我在这里做错了什么?

qrtest.py:

from kivy.app import App
from kivy.uix.image import Image
from kivy.clock import Clock
from kivy.graphics.texture import Texture

from kivy.uix.boxlayout import BoxLayout
from kivy.core.window import Window

import cv2
import os


class KivyCamera(Image):
    def dostart(self, capture, fps, **kwargs):
        self.capture = capture
        Clock.schedule_interval(self.update, 1.0 / fps)

    def update(self, dt):
        ret, frame = self.capture.read()
        if ret:
            # convert it to texture
            buf1 = cv2.flip(frame, 0)
            buf = buf1.tostring()
            image_texture = Texture.create(
                size=(frame.shape[1], frame.shape[0]), colorfmt='bgr')
            image_texture.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte')
            # display image from the texture
            self.texture = image_texture


capture = None

class QrtestHome(BoxLayout):

    def init_qrtest(self):
        pass

    def dostart(self, *largs):
        global capture
        capture = cv2.VideoCapture(0)
        my_camera = KivyCamera(capture=capture, fps=10, )
        my_camera.dostart(capture,10)

    def doexit(self):
        global capture

        if capture != None:
            capture.release()

        os._exit(0)


class qrtestApp(App):
    def build(self):
        Window.clearcolor = (.4,.4,.4,1)
        Window.size = (400, 300)
        homeWin = QrtestHome()
        homeWin.init_qrtest()
        return homeWin
qrtestApp().run()

和 qrtest.kv 文件:

<QrtestHome>:

    BoxLayout:
        orientation: "vertical"

        Label:
            height: 20
            size_hint_y: None
            text: 'Testing the camera'

        KivyCamera:
            canvas:
                Color:
                    rgb: (0, 0.6, 0.6)

                Rectangle:
                    texture: self.texture
                    pos: (50, 30)
                    size: (300, 240)


            height: 260
            id: qrcam

        BoxLayout:
            orientation: "horizontal"
            height: 20
            size_hint_y: None

            Button:
                id: butt_start
                size_hint: 0.5,1
                text: "start"
                on_press: root.dostart()

            Button:
                id: butt_exit
                text: "quit"
                size_hint: 0.5,1
                on_press: root.doexit()
4

0 回答 0