带有WebRTC的OpenCV python建模服务器

2024-06-11 20:04:47 发布

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

我对WebRTC有一些了解。我知道它主要用于两个对等方的通信,但我希望我的python服务器接收它的流,并对每个帧进行一些数学计算,然后将流发送回用户

我有OpenCV模型,它与openCV videoCapture技术一起工作,但我不想将它与webRTC集成,并将结果从python服务器发送回用户

我的问题是,如何使WebRTC正确地与python一起工作。我发现了关于aiortc,这是一个针对webRTC对等机的python实现,但它在几个用户连接方面存在一些问题,我需要做一些其他的事情

是否有其他方法将openCV模型与WebRTC流集成


Tags: 方法用户模型服务器事情opencv技术服务器发送
1条回答
网友
1楼 · 发布于 2024-06-11 20:04:47

如果您正在寻找使用WebRTC将帧流式传输到客户端的更快、最简单的方法,那么可以使用myVidGearPython库的WebGear_RTC在后台利用WebRTC技术,并且还基于aiortc-Web实时通信库(WebRTC)和对象实时通信库(ORTC)

要求:仅适用于Python 3.6+。

# install VidGear
python3 -m pip install vidgear[asyncio]
python3 -m pip install aiortc

然后您可以使用这个完整的python示例,它在网络上的任何浏览器上运行地址为http://<host-machine ip>:8000/的视频服务器,只需几行代码:

# import necessary libs
import uvicorn, asyncio, cv2
from av import VideoFrame
from aiortc import VideoStreamTrack
from aiortc.mediastreams import MediaStreamError
from vidgear.gears.asyncio import WebGear_RTC
from vidgear.gears.asyncio.helper import reducer

# initialize WebGear_RTC app without any source
web = WebGear_RTC(logging=True)

# create your own Bare-Minimum Custom Media Server
class Custom_RTCServer(VideoStreamTrack):
    """
    Custom Media Server using OpenCV, an inherit-class
    to aiortc's VideoStreamTrack.
    """

    def __init__(self, source=None):

        # don't forget this line!
        super().__init__()

        # initialize global params
        self.stream = cv2.VideoCapture(source)

    async def recv(self):
        """
        A coroutine function that yields `av.frame.Frame`.
        """
        # don't forget this function!!!

        # get next timestamp
        pts, time_base = await self.next_timestamp()

        # read video frame
        (grabbed, frame) = self.stream.read()

        # if NoneType
        if not grabbed:
            return MediaStreamError

        # reducer frames size if you want more performance otherwise comment this line
        frame = await reducer(frame, percentage=30)  # reduce frame by 30%

        # contruct `av.frame.Frame` from `numpy.nd.array`
        av_frame = VideoFrame.from_ndarray(frame, format="bgr24")
        av_frame.pts = pts
        av_frame.time_base = time_base

        # return `av.frame.Frame`
        return av_frame

    def terminate(self):
        """
        Gracefully terminates VideoGear stream
        """
        # don't forget this function!!!

        # terminate
        if not (self.stream is None):
            self.stream.release()
            self.stream = None


# assign your custom media server to config with adequate source (for e.g. foo.mp4)
web.config["server"] = Custom_RTCServer(source="foo.mp4")

# run this app on Uvicorn server at address http://0.0.0.0:8000/
uvicorn.run(web(), host="0.0.0.0", port=8000)

# close app safely
web.shutdown()

Documentation

如果仍然得到一些错误,则在其GitHub repo中引发一个issue here

相关问题 更多 >