在tornado服务器上创建视频分发,客户端用websocket连接服务端接收视频流并显示。
1、插上USB摄像头,先用工具查看usb占用的哪个接口:
USB摄像头占用video74端口。
2、添加tornado调用摄像头,实时把图像发送给ws连接对象:
JPEG_HEADER = "data:image/jpeg;base64,"
cap = cv2.VideoCapture(74)
def get_image_dataurl():
ret, frame = cap.read()
r, buf = cv2.imencode(".jpeg", frame)
dat = Image.fromarray(np.uint8(buf)).tobytes()
img_date_url = JPEG_HEADER + str(base64.b64encode(dat))[2:-1]
return img_date_url
class CaptureHandler(RequestHandler):
def get(self, *args, **kwargs):
self.render("capture.html")
class VideoHandler(WebSocketHandler):
def on_message(self, message):
self.write_message({"img": get_image_dataurl()})
3、创建网页文件如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>display</title>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
<script>
var address = "192.168.3.232";
var port = 9000;
var ws = new WebSocket("ws://192.168.3.232:9000/video");
var canvas = document.getElementById("canvas");
var start = document.getElementById("start");
var timer = setInterval(function () {
if (ws.readyState == 1){
ws.send("msg");
clearInterval(timer);
}
},10);
ws.onmessage = function (res) {
console.log("接收到数据");
var img_src = JSON.parse(res.data)["img"];
var img = new Image();
img.src = img_src;
var ctx = canvas.getContext("2d");
img.onload = function(){
canvas.setAttribute("width",img.width);
canvas.setAttribute("height",img.height);
ctx.drawImage(img,0,0,600,800);
}
ws.send("msg");
}
</script>
</html>
3、添加路由:
from views.capture import CaptureHandler as capture_get
from views.capture import VideoHandler as vide_capt
admin_urls = [
(r"/", app_index),
(r"/chat", app_chat),
(r"/can", app_can_get),
(r"/can_test", app_can_test),
(r"/capture", capture_get),
(r"/video", vide_capt)
]
4、服务运行后打开网址:
http://192.168.3.232:9000/capture
效果如下:
5、用手机打开网址:
6、cpu占用如下图:
视频非常流畅。