Python normalize images

21 Python code examples are found related to " normalize images". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: cifar10_objectDetection.py    From Deep-Learning-By-Example with MIT License 8 votes vote down vote up
def normalize_images(images):
    # initial zero ndarray
    normalized_images = np.zeros_like(images.astype(float))

    # The first images index is number of images where the other indices indicates
    # hieight, width and depth of the image
    num_images = images.shape[0]

    # Computing the minimum and maximum value of the input image to do the normalization based on them
    maximum_value, minimum_value = images.max(), images.min()

    # Normalize all the pixel values of the images to be from 0 to 1
    for img in range(num_images):
        normalized_images[img, ...] = (images[img, ...] - float(minimum_value)) / float(maximum_value - minimum_value)

    return normalized_images


# encoding the input images. Each image will be represented by a vector of zeros except for the class index of the image
# that this vector represents. The length of this vector depends on number of classes that we have
# the dataset which is 10 in CIFAR-10 
Example 2
Source File: video.py    From avocado-virt with GNU General Public License v2.0 6 votes vote down vote up
def normalize_images(self, input_dir):
        """
        Normalize images of different sizes so we can encode a video from them.

        :param input_dir: Directory with images to be normalized.
        """
        image_size = self.get_most_common_image_size(input_dir)
        if image_size is None:
            image_size = (800, 600)

        if self.verbose:
            log.debug('Normalizing image files to size: %s' % (image_size,))
        image_files = glob.glob(os.path.join(input_dir, '*.jpg'))
        for f in image_files:
            i = Image.open(f)
            if i.size != image_size:
                i.resize(image_size).save(f) 
Example 3
Source File: base_provider.py    From cluster-loss-tensorflow with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def normalize_images(self, images, normalization_type):
        """
        Args:
            images: numpy 4D array
            normalization_type: `str`, available choices:
                - divide_255
                - divide_256
                - by_chanels
        """
        if normalization_type == 'divide_255':
            images = images / 255
        elif normalization_type == 'divide_256':
            images = images / 256
        elif normalization_type == 'by_chanels':
            images = images.astype('float64')
            # for every channel in image(assume this is last dimension)
            for i in range(images.shape[-1]):
                images[:, :, :, i] = ((images[:, :, :, i] - self.images_means[i]) /
                                       self.images_stds[i])
        else:
            raise Exception("Unknown type of normalization")
        return images 
Example 4
Source File: googlelandmarks.py    From models with Apache License 2.0 6 votes vote down vote up
def NormalizeImages(images, pixel_value_scale=0.5, pixel_value_offset=0.5):
  """Normalize pixel values in image.

  Output is computed as
  normalized_images = (images - pixel_value_offset) / pixel_value_scale.

  Args:
    images: `Tensor`, images to normalize.
    pixel_value_scale: float, scale.
    pixel_value_offset: float, offset.

  Returns:
    normalized_images: `Tensor`, normalized images.
  """
  images = tf.cast(images, tf.float32)
  normalized_images = tf.math.divide(
      tf.subtract(images, pixel_value_offset), pixel_value_scale)
  return normalized_images 
Example 5
Source File: base_provider.py    From auptimizer with GNU General Public License v3.0 6 votes vote down vote up
def normalize_images(images, normalization_type, meanstd=None):
		"""
		Args:
			images: numpy 4D array
			normalization_type: `str`, available choices:
				- divide_255
				- divide_256
				- by_channels
			meanstd
		"""
		if normalization_type is not None:
			if normalization_type == 'divide_255':
				images = images / 255
			elif normalization_type == 'divide_256':
				images = images / 256
			elif normalization_type == 'by_channels':
				images = images.astype('float64')
				# for every channel in image(assume this is last dimension)
				means, stds = meanstd
				for i in range(images.shape[-1]):
					images[:, :, :, i] = ((images[:, :, :, i] - means[i]) / stds[i])
			else:
				raise Exception('Unknown type of normalization')
		return images 
Example 6
Source File: video_maker.py    From avocado-vt with GNU General Public License v2.0 6 votes vote down vote up
def normalize_images(self, input_dir):
        """
        Normalize images of different sizes so we can encode a video from them.

        :param input_dir: Directory with images to be normalized.
        """
        image_size = self.get_most_common_image_size(input_dir)
        if not isinstance(image_size, (tuple, list)):
            image_size = (800, 600)
        else:
            if image_size[0] < 640:
                image_size = 640
            if image_size[1] < 480:     # is list pylint: disable=E1136
                image_size = 480

        if self.verbose:
            logging.debug('Normalizing image files to size: %s' % (image_size,))
        image_files = glob.glob(os.path.join(input_dir, '*.jpg'))
        for f in image_files:
            i = PIL.Image.open(f)
            if i.size != image_size:
                i.resize(image_size).save(f) 
Example 7
Source File: tvnet.py    From tvnet_pytorch with MIT License 6 votes vote down vote up
def normalize_images(self, x1, x2):
        min_x1 = x1.min(3)[0].min(2)[0].min(1)[0]
        max_x1 = x1.max(3)[0].max(2)[0].max(1)[0]

        min_x2 = x2.min(3)[0].min(2)[0].min(1)[0]
        max_x2 = x2.max(3)[0].max(2)[0].max(1)[0]

        min_val = torch.min(min_x1, min_x2)
        max_val = torch.max(max_x1, max_x2)

        den = max_val - min_val

        expand_dims = [-1 if i == 0 else 1 for i in range(len(x1.shape))]
        min_val_ex = min_val.view(*expand_dims)
        den_ex = den.view(*expand_dims)

        x1_norm = torch_where(den > 0, 255. * (x1 - min_val_ex) / den_ex, x1)
        x2_norm = torch_where(den > 0, 255. * (x2 - min_val_ex) / den_ex, x2)

        return x1_norm, x2_norm 
Example 8
Source File: base_data_provider.py    From uai-sdk with Apache License 2.0 6 votes vote down vote up
def normalize_images(images, normalization_type):
        """
        Args:
            images: numpy 4D array
            normalization_type: `str`, available choices:
                - divide_255
                - divide_256
                - by_chanels
        """
        if normalization_type == 'divide_255':
            images = images / 255
        elif normalization_type == 'divide_256':
            images = images / 256
        elif normalization_type is None:
            pass
        else:
            raise Exception("Unknown type of normalization")
        return images 
Example 9
Source File: imageFilters.py    From airlab with Apache License 2.0 5 votes vote down vote up
def normalize_images(fixed_image, moving_image):
    """
    Noramlize image intensities by extracting joint minimum and dividing by joint maximum

    Note: the function is inplace

    fixed_image (Image): fixed image
    moving_image (Image): moving image
    return (Image, Image): normalized images
    """
    fixed_min = fixed_image.image.min()
    moving_min = moving_image.image.min()

    min_val = min(fixed_min, moving_min)

    fixed_image.image -= min_val
    moving_image.image -= min_val

    moving_max = moving_image.image.max()
    fixed_max = fixed_image.image.max()
    max_val = max(fixed_max, moving_max)

    fixed_image.image /= max_val
    moving_image.image /= max_val

    return (fixed_image, moving_image) 
Example 10
Source File: base_data_provider.py    From uai-sdk with Apache License 2.0 5 votes vote down vote up
def normalize_all_images_by_chanels(self, initial_images):
        """

        :param initial_images:
        :return:
        """
        new_images = np.zeros(initial_images.shape)
        for i in range(initial_images.shape[0]):
            new_images[i] = self.normalize_image_by_chanel(initial_images[i])
        return new_images 
Example 11
Source File: utils.py    From img2imgGAN with MIT License 5 votes vote down vote up
def normalize_images(images):
   """Normalizes images into the range [-1, 1]

   Args:
      images: ndarray
   """
   return images / 127.5 - 1.0 
Example 12
Source File: base_provider.py    From densenet-sdr with MIT License 5 votes vote down vote up
def normalize_all_images_by_chanels(self, initial_images):
        new_images = np.zeros(initial_images.shape)
        for i in range(initial_images.shape[0]):
            new_images[i] = self.normalize_image_by_chanel(initial_images[i])
        return new_images 
Example 13
Source File: dataset.py    From rafiki with Apache License 2.0 5 votes vote down vote up
def normalize_images(self, images, mean=None, std=None):
        '''
            Normalize all images.

            If mean `mean` and standard deviation `std` are `None`, they will be computed on the images.

            :param images: (N x width x height x channels) array-like of images to resize
            :param float[] mean: Mean for normalization, by channel
            :param float[] std: Standard deviation for normalization, by channel
            :returns: (images, mean, std)
        '''
        if len(images) == 0:
            return (images, mean, std)

        # Convert to [0, 1]
        images = np.asarray(images) / 255

        if mean is None:
            mean = np.mean(images, axis=(0, 1, 2)).tolist() # shape = (channels,)
        if std is None:
            std = np.std(images, axis=(0, 1, 2)).tolist() # shape = (channels,)

        # Normalize all images
        images = (images - mean) / std

        return (images, mean, std) 
Example 14
Source File: ImageServer.py    From DeepAlignmentNetwork with MIT License 5 votes vote down vote up
def NormalizeImages(self, imageServer=None):
        self.imgs = self.imgs.astype(np.float32)

        if imageServer is None:
            self.meanImg = np.mean(self.imgs, axis=0)
        else:
            self.meanImg = imageServer.meanImg

        self.imgs = self.imgs - self.meanImg
        
        if imageServer is None:
            self.stdDevImg = np.std(self.imgs, axis=0)
        else:
            self.stdDevImg = imageServer.stdDevImg
        
        self.imgs = self.imgs / self.stdDevImg

        from matplotlib import pyplot as plt  

        meanImg = self.meanImg - self.meanImg.min()
        meanImg = 255 * meanImg / meanImg.max()  
        meanImg = meanImg.astype(np.uint8)   
        if self.color:
            plt.imshow(np.transpose(meanImg, (1, 2, 0)))
        else:
            plt.imshow(meanImg[0], cmap=plt.cm.gray)
        plt.savefig("../meanImg.jpg")
        plt.clf()

        stdDevImg = self.stdDevImg - self.stdDevImg.min()
        stdDevImg = 255 * stdDevImg / stdDevImg.max()  
        stdDevImg = stdDevImg.astype(np.uint8)   
        if self.color:
            plt.imshow(np.transpose(stdDevImg, (1, 2, 0)))
        else:
            plt.imshow(stdDevImg[0], cmap=plt.cm.gray)
        plt.savefig("../stdDevImg.jpg")
        plt.clf() 
Example 15
Source File: normalization.py    From imgaug with MIT License 5 votes vote down vote up
def normalize_images(images):
    if images is None:
        return None
    if ia.is_np_array(images):
        if images.ndim == 2:
            return images[np.newaxis, ..., np.newaxis]
        if images.ndim == 3:
            return images[..., np.newaxis]
        return images
    if ia.is_iterable(images):
        result = []
        for image in images:
            assert image.ndim in [2, 3], (
                "Got a list of arrays as argument 'images'. Expected each "
                "array in that list to have 2 or 3 dimensions, i.e. shape "
                "(H,W) or (H,W,C). Got %d dimensions "
                "instead." % (image.ndim,))

            if image.ndim == 2:
                result.append(image[..., np.newaxis])
            else:
                result.append(image)
        return result
    raise ValueError(
        "Expected argument 'images' to be any of the following: "
        "None or array or iterable of array. Got type: %s." % (
            type(images),)) 
Example 16
Source File: preprocessing.py    From models with Apache License 2.0 4 votes vote down vote up
def normalize_images(features: tf.Tensor,
                     mean_rgb: Tuple[float, ...] = MEAN_RGB,
                     stddev_rgb: Tuple[float, ...] = STDDEV_RGB,
                     num_channels: int = 3,
                     dtype: tf.dtypes.DType = tf.float32,
                     data_format: Text = 'channels_last') -> tf.Tensor:
  """Normalizes the input image channels with the given mean and stddev.

  Args:
    features: `Tensor` representing decoded images in float format.
    mean_rgb: the mean of the channels to subtract.
    stddev_rgb: the stddev of the channels to divide.
    num_channels: the number of channels in the input image tensor.
    dtype: the dtype to convert the images to. Set to `None` to skip conversion.
    data_format: the format of the input image tensor
                 ['channels_first', 'channels_last'].

  Returns:
    A normalized image `Tensor`.
  """
  # TODO(allencwang) - figure out how to use mean_image_subtraction and
  # standardize_image on batches of images and replace the following.
  if data_format == 'channels_first':
    stats_shape = [num_channels, 1, 1]
  else:
    stats_shape = [1, 1, num_channels]

  if dtype is not None:
    features = tf.image.convert_image_dtype(features, dtype=dtype)

  if mean_rgb is not None:
    mean_rgb = tf.constant(mean_rgb,
                           shape=stats_shape,
                           dtype=features.dtype)
    mean_rgb = tf.broadcast_to(mean_rgb, tf.shape(features))
    features = features - mean_rgb

  if stddev_rgb is not None:
    stddev_rgb = tf.constant(stddev_rgb,
                             shape=stats_shape,
                             dtype=features.dtype)
    stddev_rgb = tf.broadcast_to(stddev_rgb, tf.shape(features))
    features = features / stddev_rgb

  return features