对单个图像和 image_dataset_from_directory 进行 Tensorflow 推理

问题描述 投票:0回答:1

我已经训练了一个 CNN,并有一个脚本,可以让我对使用 image_dataset_from_directory 传入的批量图像进行推理。我这样做的核心是使用以下代码:

import numpy as np
import os
import tensorflow as tf
from tensorflow.keras.preprocessing import image_dataset_from_directory
from keras.preprocessing import image
import cv2
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix

BATCH_SIZE = 32
IMG_SIZE = (96, 96)

validation_dataset = image_dataset_from_directory(validation_dir,                            batch_size=BATCH_SIZE,                              image_size=IMG_SIZE,                                            shuffle=False)

class_labels = np.concatenate([y for x, y in validation_dataset], axis=0)

paths = validation_dataset.file_paths
AUTOTUNE = tf.data.AUTOTUNE
validation_dataset = validation_dataset.prefetch(buffer_size=AUTOTUNE)

loaded_model = tf.keras.models.load_model('/Volumes/trained_models/classification/exported-models/mobilenet2_mu_classifier_V0.02')
predictions = loaded_model.predict(validation_dataset,batch_size=BATCH_SIZE).flatten()

# Apply a sigmoid since our model returns logits
probabilities = tf.nn.sigmoid(predictions)
predictions = tf.where(probabilities < 0.5, 0, 1)

我现在想做的是修改此脚本以对我单独加载的单个图像执行推理。

我尝试过的代码是:

import os
import math
import numpy as np
from PIL import Image
import tensorflow as tf
from tensorflow.keras.utils import img_to_array
from skimage import io

size = 96

# image_path, xmin, ymin, xmax and ymax come from a database query.
img = Image.open(image_path) 
img_crop = img.crop((xmin, ymin, xmax, ymax))
img_crop.resize((size,size))

model_path = '/Volumes/trained_models/classification/exported-models/mobilenet2_mu_classifier_V0.02'
loaded_model = tf.keras.models.load_model(model_path)
img_array = img_to_array(img_crop, data_format='channels_last')

try:
    prediction_logit = loaded_model.predict(img_array, batch_size=1, verbose=1)
except tf.errors.ValueError as e:
    print('TF value error')

但是,我无法让它产生预测。 try- except 块不会抛出错误,但

prediction_logit = loaded_model...
行会默默地失败。我不确定我哪里出了问题,或者为什么我能够让上面的顶部代码产生预测,但不能让这个较低的块产生预测。任何帮助将不胜感激!

conv-neural-network tensorflow2.0 prediction inference
1个回答
0
投票

所以我正在尝试学习 TF,我偶然发现了这个页面 - https://keras.io/examples/vision/image_classification_from_scratch/

他们提到了在单个图像上加载和运行推理的确切方法。就我而言,我正在处理多标签分类器,下面的代码块帮助我得到了我想要的 -

# image_size - already defined in format(height, width) that all my 
# images were transformed and trained on 

img = keras.utils.load_img('drive/MyDrive/abcdef.jpg', target_size=image_size)
img_array = keras.utils.img_to_array(img)
img_array = tf.expand_dims(img_array, 0)  # Create batch axis

img_predictions = model.predict(img_array)

pred_label = class_names[np.argmax(np.round(img_predictions,2))]
print(" Predicted label is :: "+ pred_label)

#if you also want to display the image that was passed use the code below
plt.imshow(img)

© www.soinside.com 2019 - 2024. All rights reserved.