我使用keras
和tensorflow
创建了一个人脸识别模型,现在我试图将它转换为使用flask和python的web应用程序。我的要求是,我需要在网页上显示一个实时网络摄像头,通过点击一个按钮,它应该拍照并将其保存到指定目录,并使用该图片应用程序应该识别该人。如果在数据集中找不到该人,则应在网页上显示已发现未知身份的消息。为了完成这项工作,我已经开始学习烧瓶了,在那之后,当涉及到要求时,对我来说非常困难。有人帮我解决了这个问题。
您想要做的是使用网络摄像头流与Flask一起流式传输,并使用机器学习处理它。您在烧瓶中使用Web服务器的主脚本将允许您加载index.html文件,然后通过/ video_feed路径流式传输每个帧:
from flask import Flask, render_template, Response, jsonify
from camera import VideoCamera
import cv2
app = Flask(__name__)
video_stream = VideoCamera()
@app.route('/')
def index():
return render_template('index.html')
def gen(camera):
while True:
frame = camera.get_frame()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
@app.route('/video_feed')
def video_feed():
return Response(gen(video_stream),
mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
app.run(host='127.0.0.1', debug=True,port="5000")
然后你需要VideoCamera类,你将处理每一帧,并在那里你可以在帧上进行你想要的每一个预测或处理。 camera.py文件:
class VideoCamera(object):
def __init__(self):
self.video = cv2.VideoCapture(0)
def __del__(self):
self.video.release()
def get_frame(self):
ret, frame = self.video.read()
# DO WHAT YOU WANT WITH TENSORFLOW / KERAS AND OPENCV
ret, jpeg = cv2.imencode('.jpg', frame)
return jpeg.tobytes()
最后,在html文件index.html(在模板文件夹中)显示视频流的页面:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Video Stream</title>
</head>
<body>
<img src="{{ url_for('video_feed') }}" />
</body>
</html>
from flask import Flask,request,jsonify
import numpy as np
import cv2
import tensorflow as tf
import base64
app = Flask(__name__)
graph = tf.get_default_graph()
@app.route('/')
def hello_world():
return """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<video id="video" width="640" height="480" autoplay></video>
<button id="snap">Snap Photo</button>
<canvas id="canvas" width="640" height="480"></canvas>
</body>
<script>
var video = document.getElementById('video');
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
//video.src = window.URL.createObjectURL(stream);
video.srcObject = stream;
video.play();
});
}
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var video = document.getElementById('video');
// Trigger photo take
document.getElementById("snap").addEventListener("click", function() {
context.drawImage(video, 0, 0, 640, 480);
var request = new XMLHttpRequest();
request.open('POST', '/submit?image=' + video.toString('base64'), true);
request.send();
});
</script>
</html>
"""
# HtmlVideoElement
@app.route('/test',methods=['GET'])
def test():
return "hello world!"
@app.route('/submit',methods=['POST'])
def submit():
image = request.args.get('image')
print(type(image))
return ""`
我这样做了,但问题是,当在装饰器中调用API / submit时,我在打印图像变量的类型时将我的图像存储为HTMLVideoElement,我不知道如何将其转换为Jpeg格式并将其用于进一步的目的