在 Kivy、python 中显示 RTSP 流

问题描述

我正在尝试设计一个用户界面,以便我可以在激活时查看我的 CCTV 流。我想在 Python 中使用 Kivy。

我尝试了一些方法,但这是我最近和最明智的尝试:

from kivy.app import App
from kivy.uix.video import Video
import time
 
 
class SimpleApp(App):
    def build(self):
 
        stream = Video(source="rtsp://admin:@10.248.158.35:554/ch0_0.264",play=True)
        return stream
 
 
if __name__ == "__main__":
    SimpleApp().run()

不幸的是它仍然抛出一个错误

[ERROR  ] [Image       ] Not found <rtsp://admin:@10.248.158.35:554/ch0_0.264>

我猜模块将流作为图像,当它寻找第一个图像时,没有一个,因为它还没有通过流。我还猜测它在找不到第一个图像后也不会继续尝试获取图像,这就是它无法自行解决的原因。是否有简单的修复或我遗漏的东西?

解决方法

答案是使用 openCV 并让调度程序获取图像:

from kivy.app import App
from kivy.uix.image import Image
from kivy.clock import Clock
from kivy.graphics.texture import Texture
import cv2


class KivyCamera(Image):
    def __init__(self,capture,fps,**kwargs):
        super(KivyCamera,self).__init__(**kwargs)
        self.capture = capture
        Clock.schedule_interval(self.update,1.0 / fps)

    def update(self,dt):
        ret,frame = self.capture.read()
        if ret:
            # convert it to texture
            buf1 = cv2.flip(frame,0)
            buf = buf1.tostring()
            image_texture = Texture.create(
                size=(frame.shape[1],frame.shape[0]),colorfmt='bgr')
            image_texture.blit_buffer(buf,colorfmt='bgr',bufferfmt='ubyte')
            # display image from the texture
            self.texture = image_texture


class CamApp(App):
    def build(self):
        self.capture = cv2.VideoCapture('rtsp://admin:@10.248.158.35:554/ch0_0.264')
        self.my_camera = KivyCamera(capture=self.capture,fps=30)
        return self.my_camera

    def on_stop(self):
        #without this,app will not exit even if the window is closed
        self.capture.release()


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