python - 慢速 kivy 应用程序无法实时查看网络摄像头
问题描述
我正在尝试制作一个 kivy 应用程序来实时显示从网络摄像头抓取的图像。它可以工作,但速度很慢,我想知道是否有人知道如何解决这个问题或知道使用不同的方法。慢,我的意思是在显示的连续图像之间有很大的延迟。
代码很简单,只包含一个矩形,从相机抓取的图像通过 texture.blit_buffer 显示在该矩形上。有一个“播放”按钮可以开始和停止图像显示。
我已经安排矩形上的纹理每 0.02 秒更新一次,并且使用 pythons 时间模块我能够对更新纹理的函数的执行进行计时。该函数大约每 0.02 秒被调用和执行一次,所以问题不在于函数本身很慢。这就是我挂断电话的地方。还有什么原因导致它更新显示的图像如此缓慢?
无论如何,这是 .py 文件
import numpy as np
import cv2
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.core.window import Window
from kivy.uix.button import Button
from kivy.graphics.texture import Texture
from kivy.clock import Clock
from kivy.properties import NumericProperty
import time
class WebcamGUI(Widget):
IsPlaying = False
Event = None
Size_x = 640
Size_y = 480
texture = Texture.create(size=(Size_x,Size_y),colorfmt='bgr')
frame = np.ones(shape=[Size_x, Size_y, 3], dtype=np.uint8)
data = frame.tostring()
texture.blit_buffer(data, colorfmt='bgr', bufferfmt='ubyte')
cap = cv2.VideoCapture(0)
t = time.time()
def GetFrame(self,dt):
ret, frame = self.cap.read()
frame1 = cv2.flip(frame, 0)
data = frame1.tostring()
self.texture.blit_buffer(data, colorfmt='bgr', bufferfmt='ubyte')
print(time.time()-self.t)
self.t = time.time()
def Play(self):
self.IsPlaying = not self.IsPlaying
if self.IsPlaying:
self.Event = Clock.schedule_interval(self.GetFrame,0.02)
else:
self.Event.cancel()
class WebcamGUIApp(App):
def build(self):
GUI = WebcamGUI()
return GUI
def on_stop(self):
self.cap.release()
if __name__ == '__main__':
Window.fullscreen = False
WebcamGUIApp().run()
cv2.destroyAllWindows()
这是 .kv 文件:
#:kivy 1.0.9
<WebcamGUI>:
canvas:
Rectangle:
pos: 100,100
size: self.Size_x,self.Size_y
texture: self.texture
ToggleButton:
pos: (10,10)
size: 100,25
text: "Play"
on_press: root.Play()
解决方案
推荐阅读
- assembly - LLVM 如何处理 x86 标志寄存器?
- c - 在 C 中,如何使用说明符标签将变量的“字符串”内容输入到文件名中以生成动态文件名
- python - 难以从 Pandas 数据框中删除多列
- go - go build 是否在二进制文件中包含非 go 文件?
- c++ - 我正在寻找一种优雅的方式来遍历具有多个深度的向量
- git - Git 提交归属于特定分支
- database - 是否可以仅在 2 个事务和 1 个资源之间生成死锁?
- php - php 将图像从一个目录复制到另一个目录
- c# - 更新数据库中的数据
- angular - 当我收到错误消息时出了什么问题:“没有导出的成员 'SearchBooksComponent'”?