为什么我在使用 Flask 时会收到内部服务器错误?
Why am I getting Internal Server Error when I'm using Flask?
我目前正在研究我的机器学习 svm_hog 模型。现在我想将我的模型连接到我的烧瓶。但是,每次我单击网页上的预测按钮时,它都会将我带到一个显示内部服务器错误的页面。我的模型工作得很好,我认为问题出在我的 Flask 代码中,但直到现在我仍然遇到错误。下面是我使用的代码,运行 烧瓶。
flask.py :
import os
from app import app
import urllib.request
from flask import Flask, flash, request, redirect, url_for, render_template
from werkzeug.utils import secure_filename
import tkinter as tk
from tkinter import filedialog
from tkinter import *
from PIL import Image, ImageTk
from tkinter.messagebox import showinfo
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def predictThis(folder_path):
from keras.models import load_model
import numpy as np
from keras.preprocessing import image
from numpy import argmax
model = load_model("HOG_SVM.npy")
img_width,img_height=550,293
abnormalities = {0:"normal", 1:"abnormal"}
test_image = image.load_img(folder_path, target_size=(img_width,img_height))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image,axis=0)
result = model.predict(test_image)
category_result = argmax(result)
return abnormalities[category_result]
app = Flask(__name__)
#flask routing
@app.route("/")
def home():
return render_template("home.html")
@app.route("/start")
def start():
return render_template("start.html")
@app.route('/start', methods=['POST'])
def upload_image():
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
if file.filename == '':
flash('No image selected for uploading')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join('static/upload', filename))
#print('upload_image filename: ' + filename)
#flash('Image successfully uploaded and displayed below')
result = predictThis('static/upload/' + filename)
if result == 'normal':
train = "NORMAL CHEST X RAY"
elif result == 'abnormal':
train = "TUBERCULOSIS CHEST X-RAY"
return render_template('start.html', output=train, filename=filename)
else:
flash('Allowed image types are -> png, jpg, jpeg, gif')
return redirect(request.url)
@app.route('/display/<filename>')
def display_image(filename):
#print('display_image filename: ' + filename)
return redirect(url_for('static', filename='upload/' + filename), code=301)
if __name__=='__main__':
app.run(debug=True)
我的 ml 型号代码 (HOG_SVM.npy):
from sklearn import svm
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from skimage import color
from imutils.object_detection import non_max_suppression
import imutils
import numpy as np
import argparse
import cv2
import os
import glob
from sklearn import metrics
from PIL import Image
from numpy import *
# define parameters of HOG feature extraction
orientations = 9
pixels_per_cell = (8, 8)
cells_per_block = (2, 2)
threshold = .3
dataset_path = r"C:\Users\user\Desktop\Train" # The path of dataset
# Read the image files:
category_im_listing = os.listdir(dataset_path) # Read all the files in the path
num_category_im = size(category_im_listing) # States the total no. of category
print("There are " + str(num_category_im) + " categories") # Prints the number value of the no.of categories dataset
data= []
labels = []
count = 0
# compute HOG features and label them:
for category in category_im_listing: # Enables reading the files in the pos_im_listing variable one by one
im_listing = os.listdir(dataset_path + "/" + category)
num_im = size(im_listing)
print("There are " + str(num_im) + " images in category " + str(count + 1))
for file in im_listing:
img = Image.open(dataset_path + "/" + category + "/" + file) # open the file
img = img.resize((150,150))
gray = img.convert('L') # convert the image into single channel
# calculate HOG for positive features
fd = hog(gray, orientations, pixels_per_cell, cells_per_block, block_norm='L2', feature_vector=True) # fd= feature descriptor
data.append(fd)
labels.append(count)
count = count + 1
# encode the labels, converting them from strings to integers
le = LabelEncoder()
labels = le.fit_transform(labels)
# Partitioning the data into training and testing splits, using 80%
# of the data for training and the remaining 20% for testing
print(" Constructing training/testing split...")
(trainData, testData, trainLabels, testLabels) = train_test_split(np.array(data), labels, train_size=0.80, test_size=0.20, random_state=42)
#%% Train the linear SVM
print(" Training Linear SVM classifier with HOG...")
model = svm.LinearSVC(multi_class='ovr')
model.fit(trainData, trainLabels)
#%% Evaluate the classifier
print(" Evaluating classifier on test data ...")
predictions = model.predict(testData)
print(classification_report(testLabels, predictions))
print("Validation Accuracy:",metrics.accuracy_score(testLabels, predictions))
# Save the model:
joblib.dump(model, 'HOG_SVM.npy')
start.html :
<form method="post" action="/start" enctype="multipart/form-data">
{% if filename %}
<img src="{{ url_for('display_image', filename=filename) }}" width="250" height="290">
<label for="actual-btn" class="center">{{output}}</label>
{% else %}
<input class="center" accept="image/*" onchange="loadFile(event)" type="file" name="file" autocomplete="off" required>
<input type="submit" value="Classify" cass="btn">
{% endif %} </form>
更新:我将 flask.py 代码中的 app.run() 行修改为 app.run(debug=True) 它向我展示了这个
* Serving Flask app "__main__" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Restarting with windowsapi reloader
An exception has occurred, use %tb to see the full traceback.
SystemExit: 1
C:\Users\user\anaconda3\lib\site-packages\IPython\core\interactiveshell.py:3426: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.
warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
在我 运行 %tb 之后,它向我展示了这个
---------------------------------------------------------------------------
SystemExit Traceback (most recent call last)
<ipython-input-8-869c29e262d1> in <module>
1 if __name__=='__main__':
----> 2 app.run(debug=True)
~\anaconda3\lib\site-packages\flask\app.py in run(self, host, port, debug, load_dotenv, **options)
988
989 try:
--> 990 run_simple(host, port, self, **options)
991 finally:
992 # reset the first request information if the development server
~\anaconda3\lib\site-packages\werkzeug\serving.py in run_simple(hostname, port, application, use_reloader, use_debugger, use_evalex, extra_files, reloader_interval, reloader_type, threaded, processes, request_handler, static_files, passthrough_errors, ssl_context)
1048 from ._reloader import run_with_reloader
1049
-> 1050 run_with_reloader(inner, extra_files, reloader_interval, reloader_type)
1051 else:
1052 inner()
~\anaconda3\lib\site-packages\werkzeug\_reloader.py in run_with_reloader(main_func, extra_files, interval, reloader_type)
337 reloader.run()
338 else:
--> 339 sys.exit(reloader.restart_with_reloader())
340 except KeyboardInterrupt:
341 pass
SystemExit: 1
if name=='main':
app.run(debug=True,port=9989,use_reloader=False)
- 使用上面的代码
- 如果你使用 jupyter notebook 做 flask app 那么我会推荐你
切换 spyder,pycharm 或 Vs 代码 IDE
- 因为与 Jupyter notebook
相比,您可以在 IDE 中轻松调试内容
我目前正在研究我的机器学习 svm_hog 模型。现在我想将我的模型连接到我的烧瓶。但是,每次我单击网页上的预测按钮时,它都会将我带到一个显示内部服务器错误的页面。我的模型工作得很好,我认为问题出在我的 Flask 代码中,但直到现在我仍然遇到错误。下面是我使用的代码,运行 烧瓶。
flask.py :
import os
from app import app
import urllib.request
from flask import Flask, flash, request, redirect, url_for, render_template
from werkzeug.utils import secure_filename
import tkinter as tk
from tkinter import filedialog
from tkinter import *
from PIL import Image, ImageTk
from tkinter.messagebox import showinfo
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def predictThis(folder_path):
from keras.models import load_model
import numpy as np
from keras.preprocessing import image
from numpy import argmax
model = load_model("HOG_SVM.npy")
img_width,img_height=550,293
abnormalities = {0:"normal", 1:"abnormal"}
test_image = image.load_img(folder_path, target_size=(img_width,img_height))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image,axis=0)
result = model.predict(test_image)
category_result = argmax(result)
return abnormalities[category_result]
app = Flask(__name__)
#flask routing
@app.route("/")
def home():
return render_template("home.html")
@app.route("/start")
def start():
return render_template("start.html")
@app.route('/start', methods=['POST'])
def upload_image():
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
if file.filename == '':
flash('No image selected for uploading')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join('static/upload', filename))
#print('upload_image filename: ' + filename)
#flash('Image successfully uploaded and displayed below')
result = predictThis('static/upload/' + filename)
if result == 'normal':
train = "NORMAL CHEST X RAY"
elif result == 'abnormal':
train = "TUBERCULOSIS CHEST X-RAY"
return render_template('start.html', output=train, filename=filename)
else:
flash('Allowed image types are -> png, jpg, jpeg, gif')
return redirect(request.url)
@app.route('/display/<filename>')
def display_image(filename):
#print('display_image filename: ' + filename)
return redirect(url_for('static', filename='upload/' + filename), code=301)
if __name__=='__main__':
app.run(debug=True)
我的 ml 型号代码 (HOG_SVM.npy):
from sklearn import svm
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from skimage import color
from imutils.object_detection import non_max_suppression
import imutils
import numpy as np
import argparse
import cv2
import os
import glob
from sklearn import metrics
from PIL import Image
from numpy import *
# define parameters of HOG feature extraction
orientations = 9
pixels_per_cell = (8, 8)
cells_per_block = (2, 2)
threshold = .3
dataset_path = r"C:\Users\user\Desktop\Train" # The path of dataset
# Read the image files:
category_im_listing = os.listdir(dataset_path) # Read all the files in the path
num_category_im = size(category_im_listing) # States the total no. of category
print("There are " + str(num_category_im) + " categories") # Prints the number value of the no.of categories dataset
data= []
labels = []
count = 0
# compute HOG features and label them:
for category in category_im_listing: # Enables reading the files in the pos_im_listing variable one by one
im_listing = os.listdir(dataset_path + "/" + category)
num_im = size(im_listing)
print("There are " + str(num_im) + " images in category " + str(count + 1))
for file in im_listing:
img = Image.open(dataset_path + "/" + category + "/" + file) # open the file
img = img.resize((150,150))
gray = img.convert('L') # convert the image into single channel
# calculate HOG for positive features
fd = hog(gray, orientations, pixels_per_cell, cells_per_block, block_norm='L2', feature_vector=True) # fd= feature descriptor
data.append(fd)
labels.append(count)
count = count + 1
# encode the labels, converting them from strings to integers
le = LabelEncoder()
labels = le.fit_transform(labels)
# Partitioning the data into training and testing splits, using 80%
# of the data for training and the remaining 20% for testing
print(" Constructing training/testing split...")
(trainData, testData, trainLabels, testLabels) = train_test_split(np.array(data), labels, train_size=0.80, test_size=0.20, random_state=42)
#%% Train the linear SVM
print(" Training Linear SVM classifier with HOG...")
model = svm.LinearSVC(multi_class='ovr')
model.fit(trainData, trainLabels)
#%% Evaluate the classifier
print(" Evaluating classifier on test data ...")
predictions = model.predict(testData)
print(classification_report(testLabels, predictions))
print("Validation Accuracy:",metrics.accuracy_score(testLabels, predictions))
# Save the model:
joblib.dump(model, 'HOG_SVM.npy')
start.html :
<form method="post" action="/start" enctype="multipart/form-data">
{% if filename %}
<img src="{{ url_for('display_image', filename=filename) }}" width="250" height="290">
<label for="actual-btn" class="center">{{output}}</label>
{% else %}
<input class="center" accept="image/*" onchange="loadFile(event)" type="file" name="file" autocomplete="off" required>
<input type="submit" value="Classify" cass="btn">
{% endif %} </form>
更新:我将 flask.py 代码中的 app.run() 行修改为 app.run(debug=True) 它向我展示了这个
* Serving Flask app "__main__" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Restarting with windowsapi reloader
An exception has occurred, use %tb to see the full traceback.
SystemExit: 1
C:\Users\user\anaconda3\lib\site-packages\IPython\core\interactiveshell.py:3426: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.
warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
在我 运行 %tb 之后,它向我展示了这个
---------------------------------------------------------------------------
SystemExit Traceback (most recent call last)
<ipython-input-8-869c29e262d1> in <module>
1 if __name__=='__main__':
----> 2 app.run(debug=True)
~\anaconda3\lib\site-packages\flask\app.py in run(self, host, port, debug, load_dotenv, **options)
988
989 try:
--> 990 run_simple(host, port, self, **options)
991 finally:
992 # reset the first request information if the development server
~\anaconda3\lib\site-packages\werkzeug\serving.py in run_simple(hostname, port, application, use_reloader, use_debugger, use_evalex, extra_files, reloader_interval, reloader_type, threaded, processes, request_handler, static_files, passthrough_errors, ssl_context)
1048 from ._reloader import run_with_reloader
1049
-> 1050 run_with_reloader(inner, extra_files, reloader_interval, reloader_type)
1051 else:
1052 inner()
~\anaconda3\lib\site-packages\werkzeug\_reloader.py in run_with_reloader(main_func, extra_files, interval, reloader_type)
337 reloader.run()
338 else:
--> 339 sys.exit(reloader.restart_with_reloader())
340 except KeyboardInterrupt:
341 pass
SystemExit: 1
if name=='main':
app.run(debug=True,port=9989,use_reloader=False)
- 使用上面的代码
- 如果你使用 jupyter notebook 做 flask app 那么我会推荐你 切换 spyder,pycharm 或 Vs 代码 IDE
- 因为与 Jupyter notebook 相比,您可以在 IDE 中轻松调试内容