本机调试一切都好用,但是部署到服务器上就报错,
# 上传文件
@app.route('/up_photo', methods=['POST'], strict_slashes=False)
def api_upload():
file_dir = os.path.join(basedir, app.config['UPLOAD_FOLDER'])
if not os.path.exists(file_dir):
os.makedirs(file_dir)
f = request.files['photo']
if f and allowed_file(f.filename):
fname = secure_filename(f.filename)
ext = fname.rsplit('.', 1)[1]
timestamp = time.time()
timestruct = time.localtime(timestamp)
ip = request.remote_addr
timeID=time.strftime('%Y-%m-%d %H_%M_%S', timestruct)
new_filename = timeID +"_"+ip+ '.' + ext
f.save(os.path.join(file_dir, new_filename))
img = image.load_img(os.path.join(file_dir, new_filename), target_size=(299, 299))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
.....
output_data = model.predict(x)
.....
newhtml = newhtml.replace("theImageDiscription", str(objinfor))
response = make_response(newhtml)
response.headers['Access-Control-Allow-Headers'] = 'Content-Type,Origin'
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Methods'] = 'POST,GET,OPTIONS'
return newhtml
#return jsonify({"success": 0, "msg": "上传成功"})
else:
return jsonify({"error": 1001, "msg": "上传失败"})
if __name__ == '__main__':
app.config['JSON_AS_ASCII'] = False
labels = load_labels("../models/retrained_labels_Chn.txt")
model = InceptionResNetV2(weights='../models/inception_resnet_v2_weights_tf_dim_ordering_tf_kernels.h5')
app.run(host='0.0.0.0', port=5000,debug=False, threaded=True )
出了如下的错
ValueError: Tensor Tensor("predictions/Softmax:0", shape=(?, 1000), dtype=float32) is not an element of this graph.
如果在究其原因是使用了动态图,没有固定,方法一在main中随意找张图调用一次model.predict(x)实例,但这样代码不好看
方法二.加global graph, model
if __name__ == '__main__':
orihtml = open('uploadImg_local.html', encoding='utf-8').read()
# 定义全局图,不然在flask中调用报错,因数tf是动态图,还有一种方法是先实际运行一下预测,之后就好用了,但是代码不好看
app.config['JSON_AS_ASCII'] = False
global graph, model
graph = tf.get_default_graph()
labels = load_labels("../models/retrained_labels_Chn.txt")
model = InceptionResNetV2(weights='../models/inception_resnet_v2_weights_tf_dim_ordering_tf_kernels.h5')
app.run(host='0.0.0.0', port=5000,debug=False, threaded=True )
在model.predict(x)之前加上with 语句,问题得以解决,主要是将动态图固定。
with graph.as_default():
output_data = model.predict(x)
---------------------
作者:babytiger
来源:CSDN
原文:https://blog.csdn.net/babytiger/article/details/90294260
版权声明:本文为博主原创文章,转载请附上博文链接!