cv2.imread
无法读取variable。我做新功能或添加一些代码行?我认为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)
答案 0 :(得分:0)
您需要按照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的另一个答案中对此进行了介绍。