我正在尝试用HTML和JS制作一个flask应用程序。它从网络摄像头中获取图像,存储在HTML画布中,然后将画布转换为数据URL,并通过Ajax将其发送到flask。我使用base64来解码数据,并使用cv2 imdecode读取数据。
我遇到的问题是我的图像的python代码根本没有执行。我的网页加载,一切正常,但当我拍照时,什么都没有发生。
另外一件事是
console.log
当在flask中呈现HTML时,JS函数不起作用,所以我不知道JS代码是否有问题。
你能看看我的html和python代码,告诉我哪里出错了吗?我确信在Ajax的URL上应该调用的python函数不会被调用。
这是发送Ajax的JS:
//Function called on pressing a html button
function takePic() {
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);//video is the video element in html which is recieving live data from webcam
var imgURL = canvas.toDataURL();
console.log(imgURL);
$.ajax({
type: "POST",
url: "http://url/take_pic", //I have doubt about this url, not sure if something specific must come before "/take_pic"
data: imgURL,
success: function(data) {
if (data.success) {
alert('Your file was successfully uploaded!');
} else {
alert('There was an error uploading your file!');
}
},
error: function(data) {
alert('There was an error uploading your file!');
}
}).done(function() {
console.log("Sent");
});
}
我对Ajax中的url参数有疑问,我认为在此之前必须有一些特定的内容
"/take_pic"
不仅仅是
"https://url"
.
这是我的巨蟒:
from flask import Flask,render_template,request
import numpy as np
import cv2
import re
import base64
import io
app = Flask(__name__,template_folder="flask templates")
@app.route('/')
def index():
return render_template('live webcam and capture.html')
@app.route('/take_pic',methods=["POST"])
def disp_pic():
data = request.data
encoded_data = data.split(',')[1]
nparr = np.fromstring(encoded_data.decode('base64'), np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
cv2.imshow(img)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == '__main__':
app.run(debug = True)