Issue
I am iterating images from a dataset(created with flow_from_dataframe) and would like to display the image using pyplot and its corresponding label
training_dataset = train_dataset_gen.flow_from_dataframe(dataframe=train_df,
directory="./Data/train/",
x_col="file",
y_col="label",
shuffle=True,
batch_size=BATCH_SIZE,
target_size=IMG_SIZE,
class_mode="sparse",
subset="training")
I am able to display the image but the label is an array of 0's and 1's.
for _ in range(len(training_dataset.filenames)):
image, label = training_dataset.next()
# display the image from the iterator
plt.imshow(image[0])
plt.title(training_dataset.)
plt.show()
How do I get the real label value?
This was solved by reversing the dictionary:
class_names=training_dataset.class_indices
new_dict={}
for key, value in class_names.items():
new_dict[value]=key
Solution
ImageDataGenerator has an attribute .class_indices. It is a dictionary of the form
{'class name': class index}
where class name is a string which is the name of the label in your dataframe label column. Class index is an integer associate with the class name. This is the values you will see when you print the labels (since you used class_mode='sparse'). For example in your dataframe if you labels were cat, dog then your class_indices would be
{'cat':0, 'dog':1}
It is convenient to reverse this dictionary as shown below
for key, value in class_dict.items():
new_dict[value]=key
now new_dict is of the form {0:'cat', 1:'dog'}. So now to modify your code as follows
for _ in range(len(training_dataset.filenames)):
image, label = training_dataset.next()
# display the image from the iterator
plt.imshow(image[0])
label_name=new_dict[label[0]] # note you are only showing the first image of the batch
plt.title(label_name)
plt.show()
Answered By - Gerry P
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.