python使用websocket借助node.js把视频流推到前端页面显示

443 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

之前也推过流到前端页面,也是用的websocket技术,但是需要另外的插件、且前端展示较为复杂。这次采用python+node.js+websocket进行推流。 1.下载node.js,如图所示为node.js文件夹 在这里插入图片描述 server.js内容如下:

let WebSocketServer = require('ws').Server,
    wss = new WebSocketServer({ port: 3303});

wss.on('connection', function (ws) {
    console.log('客户端已连接');
    ws.on('message', function (message) {
        wss.clients.forEach(function each(client) {
            client.send(message);
        });
        console.log(message.length);
    });
});

player.html文件内容如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>
    <img id="resImg" src="" />
</div>
<script src="jquery.min.js" ></script>
<script>
        let ws = new WebSocket("ws://127.0.0.1:3303/");
        ws.onopen = function(evt) {
            console.log("Connection open ...");
            ws.send("Hello WebSockets!");
        };
 
        ws.onmessage = function(evt) {
            $("#resImg").attr("src",evt.data);
            console.log( "Received Message: " + evt.data);
           // ws.close();
        };
 
        ws.onclose = function(evt) {
            console.log("Connection closed.");
        };
 
</script>
</body>
</html>

2.node环境下运行server.js文件,在node安装目录下输入cmd进行命令行,并运行命令node server.js 运行成功如下图所示: 在这里插入图片描述 在这里插入图片描述 3.执行ython代码,代码如下,因为我这个是用spyder编辑器运行的所以需要添加import nest_asyncio nest_asyncio.apply()这两行代码,如果不是spyder编辑器运行需要把这两行去掉。

# -*- coding: utf-8 -*-
"""
Created on Mon Jul 19 15:00:20 2021

@author: 24281
"""

import asyncio
import nest_asyncio
nest_asyncio.apply()
import websockets
import base64
from cv2 import cv2
import numpy as np

capture = cv2.VideoCapture("rtmp://58.200.131.2:1935/livetv/hunantv")
if not capture.isOpened():
    print('quit')
    quit()
ret, frame = capture.read()
encode_param=[int(cv2.IMWRITE_JPEG_QUALITY),95]

# 向服务器端实时发送视频截图
async def send_msg(websocket):
    global ret,frame
    while ret:
        #图像编码
        result, imgencode = cv2.imencode('.jpg', frame, encode_param)
        data = np.array(imgencode)
        img = data.tostring()

        # base64编码传输
        img = base64.b64encode(img).decode()
        await websocket.send("data:image/jpeg;base64,"+img)
        ret, frame = capture.read()
# 客户端主逻辑
async def main_logic():
    async with websockets.connect('ws://127.0.0.1:3303') as websocket:
        await send_msg(websocket)
loop = asyncio.get_event_loop()
result = loop.run_until_complete(main_logic())

4.打开player.html页面,湖南卫视拉流页面如下图所示: 在这里插入图片描述 下次加上目标检测!