【问题标题】:Flask: TypeError: Expected Ptr<cv::UMat> for argument '%s'Flask:TypeError:参数“%s”的预期 Ptr<cv::UMat>
【发布时间】:2019-10-31 10:08:27
【问题描述】:

我正在通过 html 上传img 并在打开的 cv 中对其进行处理并显示图像。我在upload_file.py 中有arg parsers。所以我直接将应用程序运行为 python3 upload_file.py --listofargs

template.html

<html>
<form action="{{ url_for('handle_data') }}" method="post">
    <input type="file" id="imageInput" name="file" enctype="multipart/form-data">
        <ul class="list-group list-group-flush">
           <li class="list-group-item">
               <button type="submit"  class="btn btn-primary">Colorize</button>
            </li>
        </ul>
</form>
<img src = {{image}}>
</html>

upload_file.py

from flask import Flask, render_template, request
import cv2
from flask import jsonify
import argparse
import numpy as np


app = Flask(__name__)

@app.route('/', methods=['POST','GET'])
def index():
   return render_template('template.html')
@app.route('/handle_data', methods=['POST','GET'])
def handle_data():
   img = request.form['file']
   image = np.array(img)
   cv2.imshow("Original", image)
   return render_template(template.html, image = image)

它是如何工作的?

  1. 我直接以python3 upload_file.py --listofargs 运行flask 应用程序,而不使用flask run 命令。

  2. 当我点击 colorize 时出现上述错误 Internal server error

如何修复错误,以便我可以通过html 正确读取上传的img 并通过flask 显示回opencv img

【问题讨论】:

  • 提供完整的错误信息,包括回溯。 |也就是说,不确定通过在服务器端调用 cv2.imshow 来实现什么(该函数需要在它执行的机器上使用 GUI),更不用说没有 cv2.waitKey 跟随它了。我还假设request.form['file'] 不包含原始像素数据,而是包含编码图像(在这种情况下,您需要先cv2.imdecode 它)。
  • 是的,你不能通过 Flask 发送一个 numpy 数组。先用cv2.imdecode()就可以显示了

标签: python image opencv flask upload


【解决方案1】:

在 Python3 中你可以这样做:

import numpy as np
import cv2
from io import BytesIO # not necessary?

def handle_data():
   img = request.form['file']

   image = cv2.imdecode(np.frombuffer(BytesIO(img).read(), np.uint8), cv2.IMREAD_UNCHANGED)

   cv2.imshow("Original", image) # Why do you need this?
   return render_template('template.html', image = image) # Don't forget the quotes?

这应该足以让您自己处理 html 渲染 [我不是这方面的专家 - 但如果其他人可以提供帮助,我会将其合并到此答案中。]

让我知道这是否适合你

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-30
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 2020-10-06
    • 2020-09-18
    • 2021-09-04
    相关资源
    最近更新 更多