最近再写一个人脸识别的程序,需要从Web前端调用摄像头拍照,然后发送给后端进行识别
总体思路是:Web前端拍照 -> 图片转为Base64 -> 发送至tornado后端 -> 后端解码,转换回PIL的Image对象
前端代码
调起摄像头
function getMedia() { let constraints = { video: {width: 300, height: 300}, audio: false }; let video = document.getElementById("video"); //这里是用作实时显示摄像头图像的canvas对象 let promise = navigator.mediaDevices.getUserMedia(constraints); promise.then(function (MediaStream) { video.srcObject = MediaStream; video.play(); }); }
拍照
function takePhoto() { let video = document.getElementById("video"); //用于实时显示摄像头画面的canvas let canvas = document.getElementById("canvas"); //用于显示拍得照片显示的canvas let ctx = canvas.getContext('2d'); ctx.drawImage(video, 0, 0, 300, 300); UploadFile() //拍完照片后调用上传函数 }
上传图片
function UploadFile(){ let canvas = document.getElementById('canvas'); console.log(canvas.toDataURL('image/jpeg')) //也可以是png jQuery.post('/Check', { img: canvas.toDataURL('image/jpeg') //转换为Base64 }).done(function(rs) { console.log(rs); document.getElementById("showName").innerHTML = rs }).fail(function(err) { console.log(err); document.getElementById("showName").innerHTML = err }); }
后端
class Check(tornado.web.RequestHandler): def get(self): self.write('错误的访问方式!') def post(self, *args, **kwargs): base64str = self.get_argument('img') //读取post参数 base64str = base64str.replace("data:image/jpeg;base64,","") //删除编码前的标记 imgstr = base64.b64decode(base64str) //解码 imgio = io.BytesIO(imgstr) img = Image.open(imgio) //转换回PIL的Image对象