为了账号安全,请及时绑定邮箱和手机立即绑定

NameError:未定义名称“read_image”

NameError:未定义名称“read_image”

Helenr 2022-06-02 15:12:23
我想用图像测试我的图像分类模型。但我得到一些错误: --> path = 'E:/My Work Elements/Thesis Related/Trash Classification/Trash New Code/test/cardboard/cardboard42.jpg'    test_single_image(path)        Traceback (most recent call last):          File "<ipython-input-15-4a6021aada0c>", line 2, in <module>            test_single_image(path)          File "<ipython-input-14-1654f8f7a46b>", line 3, in test_single_image            images = read_image(path)        NameError: name 'read_image' is not defined我使用这段代码:def test_single_image(path):  Garbage = ['cardboard','Glass','Metal','paper','plastic','Trash']  images = read_image(path)  time.sleep(.5)  bt_prediction = vgg16.predict(images)   preds = model.predict_proba(bt_prediction)  for idx, Garbage, x in zip(range(0,6), Garbage , preds[0]):   print("ID: {}, Label: {} {}%".format(idx, Garbage, round(x*100,2) ))  print('Final Decision:')  time.sleep(.5)  for x in range(3):   print('.'*(x+1))   time.sleep(.2)  class_predicted = model.predict_classes(bt_prediction)  class_dictionary = generator_top.class_indices  print(class_dictionary)  inv_map = {v: k for k, v in class_dictionary.items()}   print("Class: {}, prediction Result: {}".format(class_predicted[0], inv_map[class_predicted[0]]))   return load_img(path, target_size=(224,224))path = 'E:/My Work Elements/Thesis Related/Trash Classification/Trash New Code/test/cardboard/cardboard42.jpg'test_single_image(path)如何修复代码?
查看完整描述

2 回答

?
芜湖不芜

TA贡献1796条经验 获得超7个赞

您可以使用 keras VGG16 API 轻松获取 VGG16 模型


from keras.applications.vgg16 import VGG16

from keras.preprocessing import image

from keras.applications.vgg16 import preprocess_input

import numpy as np


model = VGG16(weights='imagenet', include_top=False)


img_path = 'elephant.jpg'

img = image.load_img(img_path, target_size=(224, 224))

x = image.img_to_array(img)

x = np.expand_dims(x, axis=0)

x = preprocess_input(x)


features = model.predict(x)

你read_image方法改变load_image方法。keras API 将调整图像大小以满足 vgg16 模型请求。


查看完整回答
反对 回复 2022-06-02
?
慕少森

TA贡献2019条经验 获得超9个赞

如果您使用 opencv 读取图像,它应该是 cv2.imread()。就我使用 vgg16 而言,应该有一个 read_image 函数之前定义,它接收任何形状的图像,将其调整为标准形状(224 * 224 * 3)并进行所需的任何其他类型的预处理。


如果您使用的是 keras 预处理,它有一个预定义的 load_img 函数,可以为您进行预处理。


例子 :


from keras.preprocessing.image import load_img

load_image(path,target_size= (224*224*3))

我的样本加载功能


from keras.preprocessing import image 

from keras.applications.imagenet_utils import decode_predictions, preprocess_input

def load_image(path): 

  img = image.load_img(path,target_size=model.input_shape[1:3]) 

  x = image.img_to_array(img) 

  x = np.expand_dims(x,axis=0) 

  x = preprocess_input(x) 

  return img,x


查看完整回答
反对 回复 2022-06-02
  • 2 回答
  • 0 关注
  • 220 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号