简体   繁体   English

flask 上传灰度图

[英]flask upload grayscale image

i'm studying flask. when i select an image file, i want to convert that image grayscale by cv2.我正在研究 flask。当我 select 一个图像文件时,我想通过 cv2 转换该图像灰度。 but cv2.imread can't read variable.cv2.imread无法读取变量。 i make new function or add some code line?我制作新的 function 或添加一些代码行? i think there is nothing to change in html app.py我认为 html app.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)

You need to make use of the cv2.imdecode function as explained in this answer then use c2.imencode to get it back to a writable stream.您需要按照此答案中的说明使用cv2.imdecode function,然后使用c2.imencode将其恢复为可写的 stream。

So I would make a function to create the grayscale image like:所以我会制作一个 function 来创建像这样的灰度图像:

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

Then if you wanted to change that image to grayscale on upload (saving it on your server in grayscale) you could modify the upload code to look more like:然后,如果您想在上传时将该图像更改为灰度(将其以灰度保存在您的服务器上),您可以修改上传代码使其看起来更像:

# ...
        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))
# ...

On a side note, you should probably be aware that using the originally uploaded filename to name the file can lead to later problems, which I've covered in another answer regarding handling duplicate filenames .附带一提,您可能应该知道使用最初上传的文件名来命名文件可能会导致以后出现问题,我已经在另一个关于处理重复文件名的答案中对此进行了介绍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM