当我在单独的文件中运行模型时,它运行良好,但是当我使用flask代码运行模型时,它给我一个错误,不知道为什么会遇到这个问题。我已经尝试了StackOverflow本身的一些解决方案,该解决方案说在分别加载模型和预测后尝试添加这些行
graph = tf.get_default_graph()
和
global graph
with graph.as_default():
但我仍然tensorflow.python.framework.errors_impl.FailedPreconditionError
这是我关于烧瓶的app.py文件
# Importing ML libs
from keras.models import load_model
from time import sleep
import tensorflow as tf
from keras.preprocessing.image import img_to_array
from keras.preprocessing import image
import cv2
import numpy as np
# ML Initializations
face_classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
classifier =load_model('Emotion_little_vgg.h5')
global graph
graph = tf.get_default_graph()
class_labels = ['Angry','Happy','Neutral','Sad','Surprise']
# Emotion Detection Function
def get_emotion():
with graph.as_default():
cap = cv2.VideoCapture(0)
ret, frame = cap.read()
labels = []
gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
faces = face_classifier.detectMultiScale(gray,1.3,5)
for (x,y,w,h) in faces:
# cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h,x:x+w]
roi_gray = cv2.resize(roi_gray,(48,48),interpolation=cv2.INTER_AREA)
# rect,face,image = face_detector(frame)
if np.sum([roi_gray])!=0:
roi = roi_gray.astype('float')/255.0
roi = img_to_array(roi)
roi = np.expand_dims(roi,axis=0)
preds = classifier.predict(roi)[0]
label=class_labels[preds.argmax()]
labels.append(label)
print(label)
return label
# label_position = (x,y)
# cv2.putText(frame,label,label_position,cv2.FONT_HERSHEY_SIMPLEX,2,(0,255,0),3)
else:
# cv2.putText(frame,'No Face Found',(20,60),cv2.FONT_HERSHEY_SIMPLEX,2,(0,255,0),3)
label = 404
return label
# cv2.imshow('Emotion Detector',frame)
# Flask Initializations
app = Flask(__name__)
@app.route('/', methods=['POST','GET'])
def index():
labels = get_emotion()
return labels[0]
if __name__== "__main__":
app.run(debug=True)
这是我的独立机器学习文件,可以单独运行,但是当与flask结合使用时会出现问题
from keras.models import load_model
from time import sleep
from keras.preprocessing.image import img_to_array
from keras.preprocessing import image
import cv2
import numpy as np
face_classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
classifier =load_model('Emotion_little_vgg.h5')
class_labels = ['Angry','Happy','Neutral','Sad','Surprise']
cap = cv2.VideoCapture(0)
while True:
# Grab a single frame of video
ret, frame = cap.read()
labels = []
gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
faces = face_classifier.detectMultiScale(gray,1.3,5)
for (x,y,w,h) in faces:
cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h,x:x+w]
roi_gray = cv2.resize(roi_gray,(48,48),interpolation=cv2.INTER_AREA)
# rect,face,image = face_detector(frame)
if np.sum([roi_gray])!=0:
roi = roi_gray.astype('float')/255.0
roi = img_to_array(roi)
roi = np.expand_dims(roi,axis=0)
# make a prediction on the ROI, then lookup the class
preds = classifier.predict(roi)[0]
label=class_labels[preds.argmax()]
label_position = (x,y)
print(label)
cv2.putText(frame,label,label_position,cv2.FONT_HERSHEY_SIMPLEX,2,(0,255,0),3)
else:
print("No faces found")
cv2.putText(frame,'No Face Found',(20,60),cv2.FONT_HERSHEY_SIMPLEX,2,(0,255,0),3)
cv2.imshow('Emotion Detector',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
这是我的完整错误消息
Traceback (most recent call last)
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\flask\app.py", line 2463, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\flask\app.py", line 2449, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\flask\app.py", line 1866, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\flask\app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\flask\app.py", line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\flask\app.py", line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\flask\app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\flask\app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\MAULI\Desktop\MOM\app.py", line 55, in index
labels = get_emotion()
File "C:\Users\MAULI\Desktop\MOM\app.py", line 38, in get_emotion
preds = classifier.predict(roi)[0]
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\keras\engine\training.py", line 1456, in predict
self._make_predict_function()
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\keras\engine\training.py", line 378, in _make_predict_function
**kwargs)
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\keras\backend\tensorflow_backend.py", line 3009, in function
**kwargs)
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\tensorflow\python\keras\backend.py", line 3201, in function
return GraphExecutionFunction(inputs, outputs, updates=updates, **kwargs)
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\tensorflow\python\keras\backend.py", line 2939, in __init__
with ops.control_dependencies(self.outputs):
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\tensorflow\python\framework\ops.py", line 5028, in control_dependencies
return get_default_graph().control_dependencies(control_inputs)
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\tensorflow\python\framework\ops.py", line 4528, in control_dependencies
c = self.as_graph_element(c)
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\tensorflow\python\framework\ops.py", line 3478, in as_graph_element
return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\tensorflow\python\framework\ops.py", line 3557, in _as_graph_element_locked
raise ValueError("Tensor %s is not an element of this graph." % obj)
ValueError: Tensor Tensor("activation_11/Softmax:0", shape=(?, 5), dtype=float32) is not an element of this graph.
答案 0 :(得分:0)
有一些替代方法可以解决此问题。有一种解决方案here可能会有所帮助。 我收集到的是flask对每个请求使用线程,因此您的模型在该特定线程中未初始化。为了解决这个问题,您需要创建一个TensorFlow会话,该会话可以按照链接中的建议在线程之间共享。