首页 > 解决方案 > 将图像从html画布发送到烧瓶python不起作用

问题描述

我正在尝试用 html 和 js 制作一个烧瓶应用程序。它从网络摄像头获取图像,存储在 html 画布中,然后将画布转换为数据 url 并通过 ajax 将其发送到烧瓶。我比使用 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)

标签: javascriptpythonhtmlflaskhtml5-canvas

解决方案


我刚刚创建了新的 python 和 html 文件并放置了类似的代码,现在它正在工作。不知道错误的确切原因,但两个代码是相同的。


推荐阅读