Skip to content

Instantly share code, notes, and snippets.

@liuhh02
Last active June 22, 2024 12:56
Show Gist options
  • Save liuhh02/2bd3f5b1ced9142d728d207f7828043e to your computer and use it in GitHub Desktop.
Save liuhh02/2bd3f5b1ced9142d728d207f7828043e to your computer and use it in GitHub Desktop.
Function to scale any image to the pixel values of [-1, 1] for GAN input
"""
scale_images.py
Function to scale any image to the pixel values of [-1, 1] for GAN input.
Author: liuhh02 https://machinelearningtutorials.weebly.com/
"""
from PIL import Image
import numpy as np
from os import listdir
def normalize(arr):
''' Function to scale an input array to [-1, 1] '''
arr_min = arr.min()
arr_max = arr.max()
# Check the original min and max values
print('Min: %.3f, Max: %.3f' % (arr_min, arr_max))
arr_range = arr_max - arr_min
scaled = np.array((arr-arr_min) / float(arr_range), dtype='f')
arr_new = -1 + (scaled * 2)
# Make sure min value is -1 and max value is 1
print('Min: %.3f, Max: %.3f' % (arr_new.min(), arr_new.max()))
return arr_new
# path to folder containing images
path = './directory/to/image/folder/'
# loop through all files in the directory
for filename in listdir(path):
# load image
image = Image.open(path + filename)
# convert to numpy array
image = np.array(image)
# scale to [-1,1]
image = normalize(image)
@liuhh02
Copy link
Author

liuhh02 commented Apr 7, 2020

@JohanRaniseth Amazing work! Thank you for sharing it here :)

@SchJas
Copy link

SchJas commented Apr 16, 2021

Hello @liuhh02, would it be possible to identify in your code what parameters I would need to change should I require a different scale of values other than [-1 1].

@liuhh02
Copy link
Author

liuhh02 commented Apr 17, 2021

Hello @liuhh02, would it be possible to identify in your code what parameters I would need to change should I require a different scale of values other than [-1 1].

Sure! This line of code scales the values to [0, 1]:
scaled = np.array((arr-arr_min) / float(arr_range), dtype='f')

So you may modify
arr_new = -1 + (scaled * 2)
accordingly to scale it to the range you require.

@SchJas
Copy link

SchJas commented Apr 17, 2021

@liuhh02 Nice approach, thank you for your input

@tarmopungas
Copy link

tarmopungas commented Mar 23, 2022

Thanks to @liuhh02 and @JohanRaniseth for the work. For anyone visiting in the future: you have to normalize based on the min and max of your whole (training) dataset, not every image individually like in the code provided above (see #950). If you normalize individually, you will lose information and be unable to reverse the process later.

I also had to make another change to the tensor2im function in util.py by changing this line to just return image_numpy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment