将python转换为kivy语言

时间:2020-05-08 22:03:47

标签: python python-3.x opencv kivy

我是python的新手,而对kivy则是新手,事实证明他们帮助我创建了此代码(如下),事实证明,在我的代码看起来运行良好之后,许多人告诉我,我的做法很好没写,我将使用.kv存在的python创建图形环境,更清楚地表明我无法实现该方法,希望您能帮助我转录它,谢谢。衷心感谢您,在代码下方,我只想抄录我要感谢的内容。

# -*- coding: utf-8 -*-
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.image import Image
from kivy.graphics.texture import Texture
from kivy.clock import Clock
import cv2

class CvCamera(App):
    def build(self):  # Construcción de interfaz de usuario, etc
        self._cap = cv2.VideoCapture(0)

        layout2 = BoxLayout(orientation='horizontal', size_hint=(1.0, 0.1))
        self.img1 = Image(size_hint=(1.0, 0.7))
        layout = BoxLayout(orientation='vertical')
        layout.add_widget(self.img1)
        layout.add_widget(layout2)

        while not self._cap.isOpened():
            pass

        Clock.schedule_interval(self.update, 1.0 / 30.0)
        return layout

    def update(self, dt):
        ret, img = self._cap.read()
        img = cv2.flip(img, 0)
        texture1 = Texture.create(size=(img.shape[1], img.shape[0]), colorfmt='bgr')
        texture1.blit_buffer(img.tostring(), colorfmt='bgr', bufferfmt='ubyte')
        self.img1.texture = texture1

if __name__ == '__main__':
    CvCamera().run()

1 个答案:

答案 0 :(得分:2)

以下是使用kv语言的等效内容:

# -*- coding: utf-8 -*-
from kivy.app import App
from kivy.lang import Builder
from kivy.graphics.texture import Texture
from kivy.clock import Clock
import cv2

kv = '''
BoxLayout:
    orientation: 'vertical'
    Image:
        id: img1
        size_hint: 1.0, 0.7
    BoxLayout:
        orientation: 'horizontal'
        size_hint: 1.0, 0.1
'''

class CvCamera(App):
    def build(self):  # Construcción de interfaz de usuario, etc
        self._cap = cv2.VideoCapture(0)

        layout = Builder.load_string(kv)

        while not self._cap.isOpened():
            pass

        Clock.schedule_interval(self.update, 1.0 / 30.0)
        return layout

    def update(self, dt):
        ret, img = self._cap.read()
        img = cv2.flip(img, 0)
        texture1 = Texture.create(size=(img.shape[1], img.shape[0]), colorfmt='bgr')
        texture1.blit_buffer(img.tostring(), colorfmt='bgr', bufferfmt='ubyte')
        self.root.ids.img1.texture = texture1

if __name__ == '__main__':
    CvCamera().run()

请注意,通常,()的{​​{1}}中的参数成为Widgets名称下方的缩进项。