Skip to content

Instantly share code, notes, and snippets.

@MLWhiz
Created June 15, 2019 04:04
Show Gist options
  • Select an option

  • Save MLWhiz/466184041674f6722829adb3980ab64a to your computer and use it in GitHub Desktop.

Select an option

Save MLWhiz/466184041674f6722829adb3980ab64a to your computer and use it in GitHub Desktop.
# A function to normalize image pixels.
def norm_img(img):
'''A function to Normalize Images.
Input:
img : Original image as numpy array.
Output: Normailized Image as numpy array
'''
img = (img / 127.5) - 1
return img
def denorm_img(img):
'''A function to Denormailze, i.e. recreate image from normalized image
Input:
img : Normalized image as numpy array.
Output: Original Image as numpy array
'''
img = (img + 1) * 127.5
return img.astype(np.uint8)
def sample_from_dataset(batch_size, image_shape, data_dir=None):
'''Create a batch of image samples by sampling random images from a data directory.
Resizes the image using image_shape and normalize the images.
Input:
batch_size : Sample size required
image_size : Size that Image should be resized to
data_dir : Path of directory where training images are placed.
Output:
sample : batch of processed images
'''
sample_dim = (batch_size,) + image_shape
sample = np.empty(sample_dim, dtype=np.float32)
all_data_dirlist = list(glob.glob(data_dir))
sample_imgs_paths = np.random.choice(all_data_dirlist,batch_size)
for index,img_filename in enumerate(sample_imgs_paths):
image = Image.open(img_filename)
image = image.resize(image_shape[:-1])
image = image.convert('RGB')
image = np.asarray(image)
image = norm_img(image)
sample[index,...] = image
return sample
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment