当我在单独的文件中运行我的模型时,一切正常,但当我用Flask代码运行我的模型时,它会报错,我不知道为什么会遇到这个问题。我已经尝试了一些来自StackOverflow的解决方案,这些解决方案建议在加载模型和预测后分别添加以下几行代码
graph = tf.get_default_graph()
和
global graphwith graph.as_default():
但我仍然得到类似这样的错误 tensorflow.python.framework.errors_impl.FailedPreconditionError
这是我的Flask的app.py文件
# 导入机器学习库from keras.models import load_modelfrom time import sleepimport tensorflow as tffrom keras.preprocessing.image import img_to_arrayfrom keras.preprocessing import imageimport cv2import numpy as np# 机器学习初始化face_classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')classifier =load_model('Emotion_little_vgg.h5')global graphgraph = tf.get_default_graph() class_labels = ['Angry','Happy','Neutral','Sad','Surprise']# 情感检测函数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初始化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_modelfrom time import sleepfrom keras.preprocessing.image import img_to_arrayfrom keras.preprocessing import imageimport cv2import numpy as npface_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: # 抓取视频的一帧 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) # 对ROI进行预测,然后查找类别 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("未找到面部") 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'): breakcap.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_appresponse = self.handle_exception(e)File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\flask\app.py", line 1866, in handle_exceptionreraise(exc_type, exc_value, tb)File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\flask\_compat.py", line 39, in reraiseraise valueFile "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\flask\app.py", line 2446, in wsgi_appresponse = self.full_dispatch_request()File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\flask\app.py", line 1951, in full_dispatch_requestrv = 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_exceptionreraise(exc_type, exc_value, tb)File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\flask\_compat.py", line 39, in reraiseraise valueFile "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\flask\app.py", line 1949, in full_dispatch_requestrv = self.dispatch_request()File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\flask\app.py", line 1935, in dispatch_requestreturn self.view_functions[rule.endpoint](**req.view_args)File "C:\Users\MAULI\Desktop\MOM\app.py", line 55, in indexlabels = get_emotion()File "C:\Users\MAULI\Desktop\MOM\app.py", line 38, in get_emotionpreds = classifier.predict(roi)[0]File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\keras\engine\training.py", line 1456, in predictself._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 functionreturn 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_dependenciesreturn 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_dependenciesc = 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_elementreturn 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_lockedraise 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.
回答: