【问题标题】:How to test one image in keras and output the prediction with its name如何在 keras 中测试一张图像并输出带有名称的预测
【发布时间】:2021-06-20 12:26:41
【问题描述】:

我已经设法用标签训练图像,但我无法用相应的图像预测单个图像并输出它。

代码如下:

labels = ['Black_Shank', 'Brown_Spot']
img_size = 224

def get_data(data_dir):
    data = []
    for label in labels:
        path = os.path.join(data_dir, label)
        class_num = labels.index(label)
        for img in os.listdir(path):
            try:
                img_arr = cv2.imread(os.path.join(path, img))[...,::-1] #convert BGR to RGB format
                resized_arr = cv2.resize(img_arr, (img_size, img_size)) # Reshaping images to preferred size
                data.append([resized_arr, class_num])
            except Exception as e:
                print(e)
    return np.array(data)

train = get_data('/Users/cynthianchabaya/Downloads/Tobacco/Basedata/Training')
val = get_data('/Users/cynthianchabaya/Downloads/Tobacco/Basedata/Testing')

model = Sequential()
model.add(Conv2D(32,3,padding="same", activation="relu", input_shape=(224,224,3)))
model.add(MaxPool2D())

model.add(Conv2D(32, 3, padding="same", activation="relu"))
model.add(MaxPool2D())

model.add(Conv2D(64, 3, padding="same", activation="relu"))
model.add(MaxPool2D())
model.add(Dropout(0.4))

model.add(Flatten())
model.add(Dense(128,activation="relu"))
model.add(Dense(2, activation="softmax"))

model.summary()

#opt = Adam(lr=0.000001)
model.compile(optimizer = "adam" , loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) , metrics = ['accuracy'])

history = model.fit(x_train,y_train,epochs = 500 , validation_data = (x_val, y_val))

acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']

epochs_range = range(500)

predictions = model.predict_classes(x_val)
predictions = predictions.reshape(1,-1)[0]
print(classification_report(y_val, predictions, target_names = ['Black_Shank (Class 0)','Brown_Spot (Class 1)']))

我遵循了一些教程,我不太了解它,但它的工作原理。哈哈。

【问题讨论】:

  • 您应该使用cv2.imread 加载一张图片,然后将其提供给model.predict_classes()
  • 你不需要from_logits = True,设置为False

标签: python tensorflow machine-learning keras deep-learning


【解决方案1】:

首先,由于您有一个 sofmax 激活函数,因此您不应在损失函数中设置 from_logits=True。下一个问题是你的模型是在 RGB 或 BGR 图像上训练的吗?您要预测的图像必须与训练模型时的图像格式相同。我假设它是在 RGB 图像上训练的,因为您使用 cv2 读取图像但转换为 RGB。 你也用缩放图像训练你的模型吗?通常它们会被缩放,因此像素在 0 到 1 的范围内。就像 image=image/255 但我没有在您的代码中看到任何重新缩放。此外,图像必须与训练图像具有相同的形状,在您的情况下看起来像 224 X 224

import cv2
import numpy as np
RGB=True # set to false if trained on BGR images
Scaled=False # set to False if your training images were not scaled
filepath=r' put the path here of the file you want to predict'
image=cv2.imread(fpath)
if RGB:
    image=cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image=cv2.resize(image, (224,224))
if scaled:
    image=image/255 # or whatever scale factor was used if any
image=np.expand_dims(image, axis=0) #input shape needs to be (1,width,height,channels)
predictions=model.predict(image) # prediction shape will be (1,2)
class_index-np.argmax(predictions)

class_index 是预测类别的整数代码,在您的情况下为 0 或 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-26
    • 2021-01-25
    • 1970-01-01
    • 2018-09-13
    • 1970-01-01
    • 2016-09-12
    相关资源
    最近更新 更多