在安卓设备上使用 Kivy 和 OpenCV 来调用摄像头并显示实时画面。
最编程
2024-10-15 12:37:59
...
编写 Kivy 应用:
创建一个简单的 Kivy 应用程序,打开摄像头并显示实时画面。这里是一个简单的示例代码:
import cv2
from kivy.graphics.texture import Texture
from kivy.uix.image import Image
from kivy.app import App
from kivy.clock import Clock
class CameraApp(App):
def __init__(self, **kwargs):
super(CameraApp, self).__init__(**kwargs)
self.capture = cv2.VideoCapture(0) # 0 表示默认摄像头
self.img = Image()
def build(self):
Clock.schedule_interval(self.update, 1.0 / 30.0) # 每秒 30 帧
return self.img
def update(self, dt):
ret, frame = self.capture.read()
if ret:
# 转换 BGR 到 RGB
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# Flip the frame horizontally
frame = cv2.flip(frame, 0)
# Convert to texture
texture = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt='rgb')
texture.blit_buffer(frame.tobytes(), colorfmt='rgb', bufferfmt='ubyte')
self.img.texture = texture
def on_stop(self):
self.capture.release()
if __name__ == '__main__':
CameraApp().run()