【发布时间】:2020-10-03 18:03:27
【问题描述】:
我正在尝试用 html 和 js 制作一个烧瓶应用程序。它从网络摄像头获取图像,存储在 html 画布中,然后将画布转换为数据 url 并通过 ajax 将其发送到烧瓶。我比使用 base64 解码数据并使用 cv2 imdecode 读取它。
我遇到的问题是我的图像的 python 代码根本没有执行。我的网页加载完毕,一切正常,但是当我拍照时,什么也没有发生。
另外还有一点就是在flask中渲染html时JS的console.log函数不起作用,所以不知道是不是我的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)
【问题讨论】:
-
是的,网址应该是
http://localhost:5000/take_pic -
Flask 中没有任何东西可以禁用控制台。您确定您实际上到达了
console.log行吗?是否有从浏览器发送的 AJAX 网络请求?您可以尝试使用浏览器的调试器来查看您的代码是否正在执行。 -
@barro32:不,URL 可以是相对的,只要一个路径就足够了。
-
但是 Flask 默认在
localhost:5000上运行,对吧?他们正在尝试从 JS 将POST到http://url/take_pic -
@Shantanu 当您说您的网页已加载时,您打算在浏览器中访问哪个 URL?
标签: javascript python html flask html5-canvas