how to extract label in processing image with


I am using map function to apply preprocessing on dataset in order to read and extract labels from file paths using but it returns the same label for all images
the file path is on the following shape where A is the label

images_ds ='/content/drive/MyDrive/prom02/dataset/train/*', shuffle=True)

images_ds = images_ds.shuffle(200)

train_size = int(image_count*0.8)
train_ds = images_ds.take(train_size)
test_ds = images_ds.skip(train_size)

def hot_encode(label):
    import string
    alphabet = list(string.ascii_uppercase)
    while i<26:
      if label==alphabet[i]:
    return label
def get_label(file_path):
    import os
    label= hot_encode(label)
    return label
def scale(image,label):
    return image/255, label
def process_image(file_path):
    label = tf.cast(get_label(file_path),tf.float32)
    img = # load the raw data from the file as a string
    img = tf.image.decode_jpeg(img)
    img = tf.image.resize(img, [320, 320])
    return tf.cast(img,tf.float32), label

train_ds =
test_ds =
for img,label in train_ds.take(1):

the result is always the encoded tensor of letter T as label
while when i use

for img in images_ds.take(2):

it returns the true label


I suggest to introduce some modifications, in order to make your code clean do not extract labels inside map function, create list of both path and labels, try this one:

from glob import glob
import string

alphabet = list(string.ascii_uppercase)
idx = range(26)
#create dict alphabet -> idx
dict_alpha = dict(tuple(zip(alphabet, idx)))

paths = glob('/content/drive/MyDrive/prom02/dataset/train/*.jpg')
labels = []
for path in paths:
  alpha = path.split("/")[-1][0]

#split paths, labels using train_test_split sklearn
train_ds =, labels))
train_ds = train_ds.shuffle(len(paths))

def process_image(file_path, label):
  img =
  img = tf.image.decode_jpeg(img)
  img = tf.cast(img,tf.float32)
  img = tf.image.resize(img, [320, 320], method = 'nearest')
  return img, tf.one_hot(label, 26)
batch = 1 #for test   

train_ds =
for img, label in train_ds.take(1):


  • You can just replace the scale mapping by img = tf.cast(img, tf.float32) inside
  • tf.image.resize(img, [320, 320]) by default the resizing method is 'bilinear' which is going change pixel values, for images i prefer tf.image.resize(img, [320, 320], method='nearest') which has no effect on the pixel values, it is based on duplications.

Answered By – Mohamed El Amine BELLEBNA

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published