将OpenCV网络摄像头集成到Kivy用户界面中


问题内容

我当前的程序是Python,并使用OpenCV。我依靠网络摄像头捕获,并且正在处理每个捕获的帧:

import cv2

# use the webcam
cap = cv2.VideoCapture(0)
while True:
    # read a frame from the webcam
    ret, img = cap.read()
    # transform image

我想创建一个带有按钮的Kivy界面(或另一个图形用户界面),并保留网络摄像头已经存在的功能。

我找到了以下示例:https :
//kivy.org/docs/examples/gen__camera__main__py.html
,但是它没有说明如何获取网络摄像头图像并使用OpenCV对其进行处理。

我找到了一个较旧的示例:http : //thezestyblogfarmer.blogspot.it/2013/10/kivy-
python-script-for-
capturing.html-

它使用“屏幕截图”功能将屏幕截图保存到磁盘。然后,我可以读取保存的文件并进行处理,但这似乎是不必要的步骤。

我还能尝试什么?


问题答案:

在以下位置找到此示例:https : //groups.google.com/forum/#!topic/kivy-
users/N18DmblNWb0

它将opencv捕获转换为kivy纹理,因此您可以在将其显示到kivy界面之前进行各种cv转换。

__author__ = 'bunkus'
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.image import Image
from kivy.clock import Clock
from kivy.graphics.texture import Texture

import cv2

class CamApp(App):

    def build(self):
        self.img1=Image()
        layout = BoxLayout()
        layout.add_widget(self.img1)
        #opencv2 stuffs
        self.capture = cv2.VideoCapture(0)
        cv2.namedWindow("CV2 Image")
        Clock.schedule_interval(self.update, 1.0/33.0)
        return layout

    def update(self, dt):
        # display image from cam in opencv window
        ret, frame = self.capture.read()
        cv2.imshow("CV2 Image", frame)
        # convert it to texture
        buf1 = cv2.flip(frame, 0)
        buf = buf1.tostring()
        texture1 = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt='bgr') 
        #if working on RASPBERRY PI, use colorfmt='rgba' here instead, but stick with "bgr" in blit_buffer. 
        texture1.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte')
        # display image from the texture
        self.img1.texture = texture1

if __name__ == '__main__':
    CamApp().run()
    cv2.destroyAllWindows()