【问题标题】:Save Image from mirror cam website using Flask使用 Flask 从镜像凸轮网站保存图像
【发布时间】:2021-09-06 19:31:22
【问题描述】:

我正在从事一个项目,我从镜像凸轮网站捕获图像并使用烧瓶将该图像保存在文件中。 我正在使用 mirror cam website 使用烧瓶获取实时网络摄像头。

flaskTest.py

from flask import Flask, render_template, request 
from datetime import datetime
import base64


app = Flask(__name__)

@app.route("/",methods=['POST','GET'])
def home():
    if request.method == 'GET':
        now = datetime.now()
        file1 = open('myfile.txt', 'w')
        file1.write("Date and Time:\t")
        file1.write(str(now))
        file1.close()

    if request.method == 'POST':
        req_data = request.get_json(force=True)
        encoded = req_data['canvasData']
        file2 = open('image.png', 'w')
        data = base64.b64decode(encoded)
        file2.write(str(data))
        file2.close()
    return render_template("index.html")
    
if __name__ == "__main__":
    app.run(host="127.0.0.1", port=5000)

我想从那个实时网络摄像头拍摄图像,所以我使用了一个 html 页面来绘制图像并发送帖子数据。

index.html

<!doctype html>
<html>
<head>
<script type="text/javascript" src="https://wybiral.github.io/code-art/projects/tiny-mirror/index.js"></script>
<link rel="stylesheet" type="text/css" href="https://wybiral.github.io/code-art/projects/tiny-mirror/index.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.js"></script>
</head>

<div class="video-wrap" hidden="hidden">
   <video id="video" playsinline autoplay></video>
</div>

<canvas hidden="hidden" id="canvas" width="640" height="480"></canvas>

<script>



function post(imgdata){
$.ajax({
    type: 'POST',
    data: imgdata,
    url: '/',
    dataType: 'json',
    async: false,
    success: function(result){
        // call the function that handles the response/results
    },
    error: function(){
    }
  });
};



'use strict';

const video = document.getElementById('video');
const canvas = document.getElementById('canvas');
const errorMsgElement = document.querySelector('span#errorMsg');

const constraints = {
  audio: false,
  video: {
    
    facingMode: "user"
  }
};

// Access webcam
async function init() {
  try {
    const stream = await navigator.mediaDevices.getUserMedia(constraints);
    handleSuccess(stream);
  } catch (e) {
    errorMsgElement.innerHTML = `navigator.getUserMedia error:${e.toString()}`;
  }
}

// Success
function handleSuccess(stream) {
  window.stream = stream;
  video.srcObject = stream;

var context = canvas.getContext('2d');
  setInterval(function(){

       context.drawImage(video, 0, 0, 640, 480);
       var canvasData = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
        post(canvasData); 
     }, 1500);
  

}

// Load init
init();

</script>

    <body>
        <p>Hint: Look at the favicon</p>
        <p>(Accept Permissions)</p>
        <p><label><input type="checkbox" name="mirror" id="mirror" /> Mirror image</label></p>
    </body>

</html>

Python 调试:

127.0.0.1 - - [07/Sep/2021 00:32:06] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [07/Sep/2021 00:32:10] "POST / HTTP/1.1" 400 -
127.0.0.1 - - [07/Sep/2021 00:32:12] "POST / HTTP/1.1" 400 -
127.0.0.1 - - [07/Sep/2021 00:32:13] "POST / HTTP/1.1" 400 -

我的问题是,我无法获取图片发布数据并将其保存在文件中。

【问题讨论】:

  • 首先你可以在 Flask 中使用print() 来查看代码的哪一部分被执行以及你在变量中得到了什么。
  • 顺便说一句:当您必须保存图像的字节数据时,使用str(data) 不是一个好主意。更好地以字节模式打开文件 - open(..., 'wb') - 并将其写入字节,而不是 str。
  • 谢谢你的一些提示,我会再试一次。

标签: python python-3.x ajax flask


【解决方案1】:

您没有正确地将数据发送到您的服务器。

它需要一个 base64 编码的图像,但您的数据有额外的位。
删除方案、媒体类型和 base64。

   var canvasData = canvas.toDataURL("image/png").replace("data:image/png;base64,", "");

您的服务器需要一个 JSON 负载

$.ajax({
    type: 'POST',
    data: JSON.stringify({canvasData:imgdata}),
    url: '/',
    dataType: 'json',
    contentType: 'application/json',
    async: false,
    success: function(result){
        // call the function that handles the response/results
    },
    error: function(){
    }
});

此外,您应该以二进制模式打开文件,而不是将数据转换为字符串以写入文件。

file2 = open('image.png', 'wb')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-02
    • 2016-11-06
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多