我的项目使用 socket.io 发送/接收数据。
我添加了 aiohttp 来帮助在浏览器上显示结果。
import asyncio
from aiohttp import web
sio = socketio.AsyncServer(async_mode='`aiohttp`')
app = web.Application()
sio.attach(app)
Run Code Online (Sandbox Code Playgroud)
我按照 https://us-pycon-2019-tutorial.readthedocs.io/aiohttp_file_uploading.html 上传图片,但无法上传视频。
def gen1():
# while True:
# if len(pm.list_image_display) > 1 :
image = cv2.imread("/home/duong/Pictures/Chess_Board.svg")
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# img = PIL.Image.new("RGB", (64, 64), color=(255,255,0))
image_pil = PIL.Image.fromarray(image)
fp = io.BytesIO()
image_pil.save(fp, format="JPEG")
content = fp.getvalue()
return content
async def send1():
print("11")
return web.Response(body=gen1(), content_type='image/jpeg')
Run Code Online (Sandbox Code Playgroud)
如何在浏览器上通过 aiohttp 显示视频?
小智 6
要在 aiohttp 中流式传输视频,您可以打开 StreamResponse 以响应获取img HTML 节点:
@routes.get('/video')
async def video_feed(request):
response = web.StreamResponse()
response.content_type = 'multipart/x-mixed-replace; boundary=frame'
await response.prepare(request)
for frame in frames('/dev/video0'):
await response.write(frame)
return response
Run Code Online (Sandbox Code Playgroud)
并以字节的形式发送您的帧:
def frames(path):
camera = cv2.VideoCapture(path)
if not camera.isOpened():
raise RuntimeError('Cannot open camera')
while True:
_, img = camera.read()
img = cv2.resize(img, (480, 320))
frame = cv2.imencode('.jpg', img)[1].tobytes()
yield b'--frame\r\nContent-Type: image/jpeg\r\n\r\n'+frame+b'\r\n'
Run Code Online (Sandbox Code Playgroud)
然而,这可能对网络有要求,因为单独发送每个帧所需的比特率很高。对于进一步压缩的实时流媒体,您可能需要使用 WebRTC 实现,例如aiortc。