|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +# @Time : 2018/2/8 16:30 |
| 3 | +# @Author : play4fun |
| 4 | +# @File : kivy_cv1.py |
| 5 | +# @Software: PyCharm |
| 6 | + |
| 7 | +""" |
| 8 | +kivy_cv1.py: |
| 9 | +https://gist.github.com/ExpandOcean/de261e66949009f44ad2 |
| 10 | +
|
| 11 | +pip install kivy |
| 12 | +
|
| 13 | +无显示 |
| 14 | +""" |
| 15 | + |
| 16 | +# coding:utf-8 |
| 17 | +from kivy.app import App |
| 18 | +from kivy.uix.image import Image |
| 19 | +from kivy.clock import Clock |
| 20 | +from kivy.graphics.texture import Texture |
| 21 | +import cv2 |
| 22 | + |
| 23 | + |
| 24 | +class KivyCamera(Image): |
| 25 | + def __init__(self, capture, fps, **kwargs): |
| 26 | + super(KivyCamera, self).__init__(**kwargs) |
| 27 | + self.capture = capture |
| 28 | + Clock.schedule_interval(self.update, 1.0 / fps) |
| 29 | + |
| 30 | + def update(self, dt): |
| 31 | + ret, frame = self.capture.read() |
| 32 | + if ret: |
| 33 | + # convert it to texture |
| 34 | + buf1 = cv2.flip(frame, 0) |
| 35 | + buf = buf1.tostring() |
| 36 | + image_texture = Texture.create( |
| 37 | + size=(frame.shape[1], frame.shape[0]), colorfmt='bgr') |
| 38 | + image_texture.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte') |
| 39 | + # display image from the texture |
| 40 | + self.texture = image_texture |
| 41 | + |
| 42 | + |
| 43 | +class CamApp(App): |
| 44 | + def build(self): |
| 45 | + self.capture = cv2.VideoCapture(1) |
| 46 | + self.my_camera = KivyCamera(capture=self.capture, fps=30) |
| 47 | + return self.my_camera |
| 48 | + |
| 49 | + def on_stop(self): |
| 50 | + # without this, app will not exit even if the window is closed |
| 51 | + self.capture.release() |
| 52 | + |
| 53 | + |
| 54 | +if __name__ == '__main__': |
| 55 | + CamApp().run() |
0 commit comments