How to save augmented images for visualization

Hi,

I’m currently using data augmentation for training my model. This is the code used in advanced keras mode for augmentation which i added a few augmentations.

def augment_image(image, label):
    # Flips the image randomly
    image = tf.image.random_flip_left_right(image)
    image = tf.image.random_flip_up_down(image)
    # Increase the image size, then randomly crop it down to
    # the original dimensions
    resize_factor = random.uniform(1, 1.2)
    new_height = math.floor(resize_factor * INPUT_SHAPE[0])
    new_width = math.floor(resize_factor * INPUT_SHAPE[1])
    image = tf.image.resize_with_crop_or_pad(image, new_height, new_width)
    image = tf.image.random_crop(image, size=INPUT_SHAPE)
    image = tfa.image.translate(image, [HSHIFT * tf.random.uniform(shape=[],minval=-1, maxval=1), VSHIFT * tf.random.uniform(shape=[],minval=-1, maxval=1)],interpolation='nearest',fill_mode='nearest')
    # Vary the brightness of the image
    image = tf.image.random_brightness(image, max_delta=0.2)
    image = tfa.image.rotate(image, MAX_ROT_ANGLE * tf.random.uniform([], dtype=tf.float32),interpolation='nearest',fill_mode='nearest')
    return image, label

train_dataset = train_dataset.map(augment_image, tf.data.experimental.AUTOTUNE)

I have downloaded the ipython notebook and i want to visualize the data augmentation which is going through.
I’m used to ImageDatagenerator() method of augmentation, there will be option to save in a dir in flow() api or flow_from_directory() api.

Is there way to save the augmented images using this method?

Thanks and Regards,
Ramson Jehu K

Hello @Ramson,

I haven’t not tested and I am not sure what is the image format but I guess you can save the images using something like openCV:

import cv2
import os

count=1
if not os.path.exists(output):
        os.makedirs(output)

def augment_image(image, label):
   ...
   cv2.imwrite(output+"/"+label+str(count)+".jpg", image) # Save frame as JPG file
   count = count + 1

Let me know if that works.

Regards,

Louis

Hi Louis,

I tried as you said. The issue is that the image is a tensor which doesn’t have numpy attribute. So i’m unable to save using opencv.
This issue is also mentioned in the following tensorflow github issue : https://github.com/tensorflow/tensorflow/issues/32842

They have suggested to use py.function to overcome this issue. But im unaware of using it. Can you please help it out?

Thanks and Regards,
Ramson Jehu K