Reputation: 136
I'm using ImageDataGenerator with flow_from_dataframe to load a dataset.
ImageDataGenerator allows you to specify a rescaling factor like this
datagen = ImageDataGenerator(rescale=1./255)
But what if I want to rescale my images in the range [-1,1]? I should do a subtraction followed by a division
images -= 128.0
images /= 128.0
How can I do these two operations in the rescale of ImageDataGenerator?
Upvotes: 0
Views: 2373
Reputation: 8112
try using rescale=1/127.5-1 or you can use pre defined processor functions such as
preprocessing_function=tf.keras.applications.mobilenet.preprocess_input
Upvotes: 2
Reputation: 5079
Keras imagedatagen rescale parameter multiplies the data with a given value. That's why it used as 1/255.0 etc.
When you execute this:
datagen = ImageDataGenerator(rescale=1./255)
Your data's mean will be 0.5 with a range 0 to 1. Now is the tricky part, you want to set your mean to 0 firstly. For that, you can use featurewise_center and samplewise_center. Now, it is done, but your data is scaled between -0.5 and 0.5
To ensure it is between -1 and 1, we will rescale it by 2/255.0 . So the last code should look like this:
datagen = ImageDataGenerator(rescale=2/255.0,
featurewise_center=True,
samplewise_center=True,)
For more details about _center parameters, you can refer the docs
Upvotes: 0
Reputation: 352
You could use a preprocessing function like this:
def rescale_img(img):
img = img.astype(np.float32) / 255.0
img = (img - 0.5) * 2
return img
and then in the rescale part you can just do this:
datagen = ImageDataGenerator(rescale=rescale_img())
Upvotes: 0