Home > front end >  is it possible to get image name from image_dataset_from_directory?
is it possible to get image name from image_dataset_from_directory?

Time:09-25

what I have is a python script to classify images using pre-trained model. first, I read the images using

VALIDATION_DATASET = image_dataset_from_directory(VALIDATION_DIR,
                                                  shuffle=True,
                                                  batch_size=BATCH_SIZE,
                                                  image_size=IMG_SIZE)

after that I divide the validation dataset into validation and test groups as in:

VAL_BATCHES = tf.data.experimental.cardinality(VALIDATION_DATASET)
TEST_DATASET = VALIDATION_DATASET.take(VAL_BATCHES // 5)
VALIDATION_DATASET = VALIDATION_DATASET.skip(VAL_BATCHES // 5)

and finally, for optimization I use prefetch:

test_dataset = TEST_DATASET.prefetch(buffer_size=AUTOTUNE)

in the testing part I use:

model_name = r"C:\model\location\pre_trained_model.h5"
model = tf.keras.models.load_model(model_name)

predictions_A = tf.where(tf.nn.sigmoid(model.predict_on_batch(image_batch_A).flatten())< 0.5, 0, 1)
predictions_B = tf.where(tf.nn.sigmoid(model.predict_on_batch(image_batch_B).flatten())< 0.5, 0, 1)
predictions_C = tf.where(tf.nn.sigmoid(model.predict_on_batch(image_batch_C).flatten())< 0.5, 0, 1)
predictions_D = tf.where(tf.nn.sigmoid(model.predict_on_batch(image_batch_D).flatten())< 0.5, 0, 1)

ALLpredictions= np.concatenate((predictions_A,predictions_B,predictions_C, predictions_D ), axis=0)


classificationRPRT = classification_report(ALLlabel_batch, ALLpredictions, target_names=CLASSES_NAMES)
print(classificationRPRT)

because tf choose images randomly, I want to know the name of the images so later I can compare the model result with separate result done manually.

CodePudding user response:

You can instead use a custom loading function with tf.data.Dataset that returns both the image and the file name:

import tensorflow as tf
from glob2 import glob

files = glob('main_folder/*/*.jpg')

def load(path):
    as_string = tf.io.read_file(path)
    as_image = tf.image.decode_image(as_string, channels=3)
    resized = tf.image.resize(as_image, (224, 224))
    normalized = tf.divide(resized, 255)
    return normalized, path

ds = tf.data.Dataset.from_tensor_slices(files).shuffle(32).map(load).batch(8)

This wil return the resized image and also the file name:

image_batch, path_batch = next(iter(ds))
  • Related