How to rescale our image using TensorFlow in Python

Hello programmers, in this tutorial, we will learn how to rescale our image using TensorFlow in Python.

We can rescale the image by using ImageDataGenerator.

ImageDataGenerator: It is a class of Keras that is used to rescale our image, rotates our image, flip our image, and many more functions.

Let’s see how we use ImageDataGenerator.

Assign the directory

We have a dataset of cat and dog images

!wget --no-check-certificate https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip

import zipfile

# Unzip the archive
local_zip = './cats_and_dogs_filtered.zip'
zip_ref = zipfile.ZipFile(local_zip, 'r')
zip_ref.extractall()

zip_ref.close()

import os

base_dir = 'cats_and_dogs_filtered'
train_dir = os.path.join(base_dir, 'train')
validation_dir = os.path.join(base_dir, 'validation')

# Directory with training cat/dog pictures
train_cats_dir = os.path.join(train_dir, 'cats')
train_dogs_dir = os.path.join(train_dir, 'dogs')

# Directory with validation cat/dog pictures
validation_cats_dir = os.path.join(validation_dir, 'cats')
validation_dogs_dir = os.path.join(validation_dir, 'dogs')

Data Preprocessing

Now we set up a data generator that will read images from our folders and convert them into a float32 tensor.

we have to set up two generators one for training and one for validation images.

We use data generator because we know that the data that goes into neuron networks should be normalized to make our model more amenable.

Originally our images are in the [0,255] range and after rescale and normalizing them our images are in the range of [0,1].

We can use ImageDataGenerator via “keras.preprocessing.image.ImageDataGenerator” class using the rescale parameter.

from tensorflow.keras.preprocessing.image import ImageDataGenerator

#images will be rescaled by 1./255.
train_datagen = ImageDataGenerator( rescale = 1.0/255. )
test_datagen  = ImageDataGenerator( rescale = 1.0/255. )


train_generator = train_datagen.flow_from_directory(train_dir,
                                                    class_mode='binary',
                                                    target_size=(250, 250))  

validation_generator =  test_datagen.flow_from_directory(validation_dir,
                                                         class_mode  = 'binary',
                                                         target_size = (250, 250))

 

Thus, we have learned how to rescale our image using TensorFlow.

Leave a Reply

Your email address will not be published.