python - 如何通过 aiohttp 在 Web 浏览器/HTML 页面上流式传输视频?

标签 python aiohttp

我的项目使用 socket.io 发送/接收数据。

我添加了 aiohttp 来帮助在浏览器上显示结果。

import asyncio
from aiohttp import web
sio = socketio.AsyncServer(async_mode='`aiohttp`')
app = web.Application()
sio.attach(app)

我关注了 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')

如何在浏览器上通过aiohttp显示视频?

最佳答案

要在 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

并以字节的形式发送你的帧:

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'

但这可能对网络要求很高,因为单独发送每个帧所需的比特率很高。对于进一步压缩的实时流,您可能需要使用 WebRTC 实现,如 aiortc .

关于python - 如何通过 aiohttp 在 Web 浏览器/HTML 页面上流式传输视频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60886118/

相关文章:

python - 如何嵌入 Evince?

python - 如何关闭 urllib2 连接?

sqlalchemy - Gino引擎未初始化

python - aiohttp - 多个 websockets,单个 session ?

python - Swagger UI 显示 API 不支持的 HTTP HEAD 方法

python - Django 迁移 ProgrammingError : syntax error at or near ""

python - 将完整字符串类型时间转换为日期时间类型 - Python

python - 为什么使用 fast_executemany=True 调用 cursor.executemany() 会导致段错误?

python - 使用 gunicorn 和 nginx 部署 aiohttp.web 应用程序

python-asyncio - 如何重用 aiohttp ClientSession 池?