Tensorflow: Stack multiple pictures into one tensor

Viewed 76

I´m quite new in the tensorflow /ML-world and I´m trying to combine multiple grayscale-images (size 214x214, format=.png) into one tf.tensor, which should represent a "bag" of images. Only the bag has a single label. I think the correct shape of the tensor should be (214,214,16). The last dimension correspond to the amount of images in the bag(=16 pictures). In a future step, multiple bags should be inserted in a tensorflow-dataset.

Does anyone know a good method for this case because my current code doesn't work due to TensorArray object is not subscriptable, but I don't know what I'm doing wrong or maybe the whole method is rubbish.

#directory with 16 png-images (RGB)
path1=r"\Train\io\M1\*.png"


images_ds=tf.data.Dataset.list_files(path1, shuffle=True)

bag = tf.TensorArray(tf.float32, size=0, dynamic_size=True)

k=0

for element in images_ds:
    
    img=tf.io.read_file(element)
    img=tf.image.decode_png(img,channels=1)
    img=tf.image.resize(img, [224,224])  
    
    bag=bag.write(k, img)
    k+=1

bag=tf.stack(bag)   
print(bag)
1 Answers

You have it close -- instead of using TensorArray as an intermediate storage, you can just use vanilla python list. Also, tf.concat() is more appropriate than tf.stack() here (tf.stack() adds an axis; tf.concat() does not).

elements = []
for element in images_ds:
  img=tf.io.read_file(element)
  # ...
  elements.append(img) # img is [244, 244, 1]
  if len(elements) == 16:
    bag = tf.concat(elements, axis=-1)  #  result is [224, 244, 16].
    elements = []
    # add bag to another storage...
Related