简体   繁体   中英

flask upload grayscale image

i'm studying flask. when i select an image file, i want to convert that image grayscale by cv2. but cv2.imread can't read variable. i make new function or add some code line? i think there is nothing to change in 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.

So I would make a function to create the grayscale image like:

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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