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

9

我的当前程序是用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,它使用“截图”函数将屏幕截图保存到磁盘上。然后,我可以读取保存的文件并对其进行处理,但这似乎是一个不必要的步骤。还有什么其他方法可以尝试?
2个回答

21

在这里找到了一个例子: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()

使用这种方法并隐藏CV窗口使应用程序比Kivy Cam示例加载更快。 - art
2
混合使用Kivy和cv.imshow是一个可怕的想法。只需删除所有的imshownamedWindow调用即可。-- 这个答案的重要部分是“纹理”和blitting的内容。 - Christoph Rackwitz
是的,这是一个糟糕的想法。我把它们留作示例。回顾起来并不必要。 - Cristian

3

注意: 我不知道OpenCV如何工作,但我找到了camera_opencv.py,这意味着有一种简单的方法可以使用它。

正如您在摄像机示例中所看到的,这是默认方式,并且当您查看相机的__init__.py时,您可以看到提供程序中的opencv,因此它可能可以直接与OpenCV一起使用。检查日志是否可以看到OpenCV被检测为提供程序。如果检测到,则应该在某处写有CameraOpenCV,并且在捕获图像时应该显示出来。

但是,如果您希望直接使用OpenCV(即cap.read()等类似的内容),则需要为提供程序编写自己的处理程序或将更多选项附加到camera_opencv文件中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接