赞
踩
代码力求简洁,没有上面基础的应该也能看懂 : )
from tornado import web,httpserver,ioloop,websocket import os import cv2 import numpy as np from PIL import Image import base64 # 定义一些基本设置 port = 10101 address = "localhost" JPEG_HEADER = "data:image/jpeg;base64," # 这个是对图片转码用的 # 开启一个摄像头 cap = cv2.VideoCapture(0) def get_image_dataurl(): # (1).从摄像头读取数据, 读取成功 ret为True,否则为False,frame里面就是一个三维数组保存图像 ret,frame = cap.read() # (2).先将数组类型编码成 jepg 类型的数据,然后转字节数组,最后将其用base64编码 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 IndexHandler(web.RequestHandler): def get(self, *args, **kwargs): self.render("index.html") class VideoHandler(websocket.WebSocketHandler): # 处理接收数据 def on_message(self, message): self.write_message({"img":get_image_dataurl()}) if __name__ == '__main__': app = web.Application(handlers=[(r"/",IndexHandler), (r"/index",IndexHandler), (r'/video',VideoHandler)], template_path=os.path.join(os.path.dirname(__file__),"ui")) http_server = httpserver.HTTPServer(app) http_server.listen(port=port,address=address) print("URL: http://{}:{}/index".format(address,port)) ioloop.IOLoop.instance().start()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>display</title> </head> <body> <!-- canvas 这个标签常用来绘制图像 --> <canvas id="canvas"></canvas> </body> <script> var address = "localhost"; var port = 10101; var ws = new WebSocket("ws://"+address+":"+port+"/video"); var canvas = document.getElementById("canvas"); var start = document.getElementById("start"); //设置一个定时10ms,等待WebSocket 连接完成 var timer = setInterval(function () { if (ws.readyState == 1){ //想服务器发送数据,请求图片,这里发送的内容随便都可以 ws.send("msg"); clearInterval(timer); } },10); //信息的回调处理函数 ws.onmessage = function (res) { //(1).首先获取到一帧帧的图片 var img_src = JSON.parse(res.data)["img"]; var img = new Image(); img.src = img_src; //(2).展示出来 var ctx = canvas.getContext("2d"); // 2维图像 canvas.setAttribute("width",img.width); canvas.setAttribute("height",img.height); ctx.drawImage(img,0,0); //后面两个0代表从坐标(0,0)的位置开始绘制图片 ws.send("msg"); } </script> </html>
由于canvas 刷新的问题,在有些浏览器可能不成功
我之前用的Google不成功,后来用QQ浏览器成功了
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。