如果您正在寻找使用 WebRTC 将帧流式传输到客户端的更快、最简单的方法,您可以使用我的VidGear Python 库的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, cv2
from vidgear.gears.asyncio import WebGear_RTC
# create your own custom streaming class
class Custom_Stream_Class:
"""
Custom Streaming using OpenCV
"""
def __init__(self, source=0):
# !!! define your own video source here !!!
self.source = cv2.VideoCapture(source)
# define running flag
self.running = True
def read(self):
# don't forget this function!!!
# check if source was initialized or not
if self.source is None:
return None
# check if we're still running
if self.running:
# read frame from provided source
(grabbed, frame) = self.source.read()
# check if frame is available
if grabbed:
# do something with your OpenCV frame here
# lets convert frame to gray for this example
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# return our gray frame
return gray
else:
# signal we're not running now
self.running = False
# return None-type
return None
def stop(self):
# don't forget this function!!!
# flag that we're not running
self.running = False
# close stream
if not self.source is None:
self.source.release()
# assign your Custom Streaming Class with adequate source (for e.g. foo.mp4)
# to `custom_stream` attribute in options parameter
options = {"custom_stream": Custom_Stream_Class(source="foo.mp4")}
# initialize WebGear_RTC app without any source
web = WebGear_RTC(logging=True, **options)
# run this app on Uvicorn server at address http://localhost:8000/
uvicorn.run(web(), host="localhost", port=8000)
# close app safely
web.shutdown()
文档
如果仍然出现错误,请在其 GitHub 存储库中提出问题。