【问题标题】:flask upload grayscale image烧瓶上传灰度图
【发布时间】:2020-09-22 04:20:12
【问题描述】:

我正在研究烧瓶。当我选择一个图像文件时,我想通过 cv2 转换该图像灰度。但cv2.imread 无法读取变量。我制作新功能或添加一些代码行?我认为html没有什么可改变的 应用程序.py

from flask import Flask, render_template, request, redirect, url_for,send_from_directory
from werkzeug.utils import secure_filename
import os

FOLDER_PATH = os.path.join('C:\\Users\\teran\\Desktop\\Ps_Sd\\uploads\\')
ALLOWED_EXTENSIONS = set([ 'png','PNG', 'jpg', 'jpeg'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = FOLDER_PATH

def allowed_file(filename):
    return '.' in filename and \
            filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file', filename=filename))
    return render_template('upload.html')
  
@app.route('/show/<filename>')
def uploaded_file(filename):
    filename = 'http://localhost:5000/uploads/' + filename
    return render_template('upload.html', filename=filename)

@app.route('/uploads/<filename>')
def send_file(filename):
    return send_from_directory(FOLDER_PATH, filename)
if __name__ == '__main__':
    app.run(debug=True)

【问题讨论】:

    标签: python flask


    【解决方案1】:

    您需要按照this answer 中的说明使用cv2.imdecode 函数,然后使用c2.imencode 将其恢复为可写流。

    所以我会创建一个函数来创建灰度图像,例如:

    import cv2
    import numpy as np
    
    def make_grayscale(in_stream):
        # Credit: https://stackoverflow.com/a/34475270
    
        #use numpy to construct an array from the bytes
        arr = np.fromstring(in_stream, dtype='uint8')
    
        #decode the array into an image
        img = cv2.imdecode(arr, cv2.IMREAD_UNCHANGED)
    
        # Make grayscale
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        
        _, out_stream = cv2.imencode('.PNG', gray)
    
        return out_stream
    

    然后,如果您想在上传时将该图像更改为灰度(将其以灰度保存在您的服务器上),您可以修改上传代码,使其看起来更像:

    # ...
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file_data = make_grayscale(file.read())
    
                with open(os.path.join(app.config['UPLOAD_FOLDER'], filename),
                          'wb') as f:
                    f.write(file_data)
    
                return redirect(url_for('uploaded_file', filename=filename))
    # ...
    

    附带说明,您可能应该知道,使用最初上传的文件名来命名文件可能会导致以后出现问题,我已经在另一个关于 handling duplicate filenames 的答案中介绍了这些问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-03
      • 2021-01-03
      • 2020-08-30
      相关资源
      最近更新 更多