【问题标题】:How to use unhashable type: ' numpy.ndarray'如何使用不可散列的类型:'numpy.ndarray'
【发布时间】: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] 代替

标签: python numpy


【解决方案1】:

你不需要字典。你想从整数到字符串,所以你真的应该使用:

labels = ['Bakpao', 'Kue Ku', 'Kembang Goyang', 'Kue Lumpur', 'Klepon']

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 labels[p[:,0]]

【讨论】:

  • 谢谢先生,但是当我尝试提交图像时出现“只有整数标量数组可以转换为标量索引”错误
猜你喜欢
  • 2012-02-19
  • 1970-01-01
  • 2020-01-24
  • 1970-01-01
  • 1970-01-01
  • 2018-04-24
  • 2018-08-03
  • 1970-01-01
相关资源
最近更新 更多