【发布时间】:2022-06-11 00:59:41
【问题描述】:
我正在尝试使用带有 cnn 模型的 Flask 进行图像识别。
app = Flask(__name__)
dic = {'Bakpao': 0, 'Kue Ku': 1, 'Kembang Goyang': 2, 'Kue Lumpur': 3, 'Klepon': 4}
model = keras.models.load_model('model.h5', custom_objects={'tf': tf})
model.make_predict_function()
def predict_label(img_path):
i = tf.keras.utils.load_img(img_path, target_size=(100,100))
i = tf.keras.utils.img_to_array(i)/255.0
i = i.reshape(1, 100,100,3)
p = model.predict(i)
return dic[p[:,0]]
@app.route("/", methods=['GET', 'POST'])
def main():
return render_template("index.html")
@app.route("/about")
def about_page():
return "Orbit Future Academy"
@app.route("/submit", methods = ['GET', 'POST'])
def get_output():
if request.method == 'POST':
img = request.files['my_image']
img_path = "static/" + img.filename
img.save(img_path)
p = predict_label(img_path)
return render_template("index.html", prediction = p, img_path = img_path)
if __name__ =='__main__':
#app.debug = True
app.run(debug = True)
当我尝试在 Flask 网络应用程序中提交我的图像以开始识别时,我收到了这个错误:
Traceback (most recent call last):
File "c:\Users\ilman\Desktop\Flask\Image-Classification-Webapp\app.py", line 38, in get_output
p = predict_label(img_path)
File "c:\Users\ilman\Desktop\Flask\Image-Classification-Webapp\app.py", line 20, in predict_label
return dic[p[:,0]]
TypeError: unhashable type: 'numpy.ndarray'
我正在使用最新的 Python、Tensorflow 和 Keras。
【问题讨论】:
-
如果您尝试通过数字 id 获取字符串标签,那么您的
dic键和值是错误的 - id 应该是键,标签应该是值。然后另一个问题是p[:,0]返回一个数组而不是一个数字......如果它是一个包含单个元素的数组,请尝试p[:,0][0]代替