本機調試一切都好用,但是部署到服務器上就報錯,
# 上傳文件
@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
版權聲明:本文爲博主原創文章,轉載請附上博文鏈接!