连续处理opencv帧,并使用gstreamer rtsp按需显示

2024-09-29 17:17:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个python脚本,它可以连续处理来自相机的图像,并在有连接的情况下通过gstreamer rtsp显示图像。虽然也有类似的帖子,我可以通过rtsp显示摄像头视频,但视频捕获机制仅在GstRtspServer.RTSPMediaFactory.on\u need\u data()方法运行时运行

理想情况下,我希望有一个继承RTSPMediaFactory类的SensorFactory类和一个捕获图像、处理图像并设置SensorFactory.frame的while循环。SensorFactory.on\u需要\u数据将返回最新的SensorFactory.frame

class SensorFactory(GstRtspServer.RTSPMediaFactory):
  def __init__(self, **properties):
    GstRtspServer.RTSPMediaFactory.__init__(self)
    self.frame = None
    ...


  def on_need_data(self, src, lenght):
    if self.frame is not None:
        data = self.frame.tostring()
        buf = Gst.Buffer.new_allocate(None, len(data), None)
        buf.fill(0, data)
        buf.duration = self.duration
        timestamp = self.number_frames * self.duration
        buf.pts = buf.dts = int(timestamp)
        buf.offset = timestamp
        self.number_frames += 1
        retval = src.emit('push-buffer', buf)

GObject.threads_init()
Gst.init(None)
server = GstServer()
loop = GObject.MainLoop()
loop.run()

cap = cv2.VideoCapture(0)
while(True):
    ret, frame = cap.read()
    server.frame = frame
    process(frame)

问题是这段代码阻塞了loop.run()。虽然我可以在_need_data()上读取帧,但这只会在有活动rtsp连接时处理视频,即使没有活动rtsp连接,我也希望处理帧

我尝试了threading.Event和loop.get_context()方法,但不确定如何将它们集成到这个场景中


Tags: 图像selfnoneloopdata视频initon

热门问题