所以我要用用户输入的上传图像创建一个有关图像分类的网站,并且该图像将在不同的python文件中进行处理,不幸的是我坚持了一个星期以上的问题
AttributeError: 'Request' object has no attribute 'file'
这是Flask的完整代码
app.py
from flask import Flask, redirect, render_template, request
from werkzeug.utils import secure_filename
import os
from Testing import predict
app = Flask(__name__)
app.config["ALLOWED_EXTENSIONS"] = ["JPEG", "JPG", "PNG", "GIF"]
app.config['UPLOAD_FOLDER'] = 'uploads'
def allowed_image(filename):
if not "." in filename:
return False
ext = filename.rsplit(".", 1)[1]
if ext.upper() in app.config["ALLOWED_EXTENSIONS"]:
return True
else:
return False
@app.route('/predict_image/', methods=['GET', 'POST'])
def render_message():
# Loading CNN model
if request.method == 'POST':
file = request.file['image_retina']
if 'file' not in request.files:
return render_template('upload.html')
if file.filename == '':
return render_template('upload.html')
if file and allowed_image(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
predict()
return render_template('upload.html')
这是处理图像的代码
Testing.py
import os
import numpy as np
from keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array
from keras.models import Sequential, load_model
import time
start = time.time()
# Define Path
test_path = 'data/test_image'
# Define image parameters
img_width, img_height = 150, 150
# Prediction Function
def predict():
model_path = './models/model.h5'
model_weights_path = './models/weights.h5'
model = load_model(model_path)
model.load_weights(model_weights_path)
x = load_img(test_path, target_size=(img_width, img_height))
x = img_to_array(x)
x = np.expand_dims(x, axis=0)
array = model.predict(x)
result = array[0]
# print(result)
answer = np.argmax(result)
if answer == 0:
print("Predicted: Drusen")
elif answer == 1:
print("Predicted: Normal")
return answer
# Calculate execution time
end = time.time()
dur = end-start
if dur < 60:
print("Execution Time:", dur, "seconds")
elif dur > 60 and dur < 3600:
dur = dur/60
print("Execution Time:", dur, "minutes")
else:
dur = dur/(60*60)
print("Execution Time:", dur, "hours")
upload.html
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Gambar</title>
</head>
<body>
<h1>Upload an Image</h1><br>
<form method="post" enctype="multipart/form-data">
<input type="file" id="image_retina" name="image_retina">
<label for="image_retina">Select image...</label><br>
<button type="submit">Upload</button><br>
<!-- <a href="/predict_image">bercanda anda</a> -->
</form>
{% if message %}
<p>{{message}}</p><br>
{% if data.shape[0] > 0 %}
<!-- {{ data.reset_index(drop = True).to_html(classes="table table-striped") | safe}} -->
{% endif %}
<p><img src="{{image_retina}}" style='width:500px' /><br>
{% endif %}
</body>
</html>
非常感谢您!
答案 0 :(得分:0)
根据API文档应该为request.files
https://flask.palletsprojects.com/en/1.1.x/api/#flask.Request.files