Python skimage.exposure.adjust_gamma() Examples

The following are 19 code examples of skimage.exposure.adjust_gamma(). 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. You may also want to check out all available functions/classes of the module skimage.exposure , or try the search function .
Example #1
Source File: prepro.py    From LapSRN-tensorflow with Apache License 2.0 6 votes vote down vote up
def brightness_multi(x, gamma=1, gain=1, is_random=False):
    """Change the brightness of multiply images, randomly or non-randomly.
    Usually be used for image segmentation which x=[X, Y], X and Y should be matched.

    Parameters
    -----------
    x : list of numpy array
        List of images with dimension of [n_images, row, col, channel] (default).
    others : see ``brightness``.
    """
    if is_random:
        gamma = np.random.uniform(1-gamma, 1+gamma)

    results = []
    for data in x:
        results.append( exposure.adjust_gamma(data, gamma, gain) )
    return np.asarray(results)


# contrast 
Example #2
Source File: prepro.py    From super-resolution-videos with The Unlicense 6 votes vote down vote up
def brightness_multi(x, gamma=1, gain=1, is_random=False):
    """Change the brightness of multiply images, randomly or non-randomly.
    Usually be used for image segmentation which x=[X, Y], X and Y should be matched.

    Parameters
    -----------
    x : list of numpy array
        List of images with dimension of [n_images, row, col, channel] (default).
    others : see ``brightness``.
    """
    if is_random:
        gamma = np.random.uniform(1-gamma, 1+gamma)

    results = []
    for data in x:
        results.append( exposure.adjust_gamma(data, gamma, gain) )
    return np.asarray(results)


# contrast 
Example #3
Source File: prepro.py    From super-resolution-videos with The Unlicense 6 votes vote down vote up
def brightness(x, gamma=1, gain=1, is_random=False):
    """Change the brightness of a single image, randomly or non-randomly.

    Parameters
    -----------
    x : numpy array
        An image with dimension of [row, col, channel] (default).
    gamma : float, small than 1 means brighter.
        Non negative real number. Default value is 1.

        - If is_random is True, gamma in a range of (1-gamma, 1+gamma).
    gain : float
        The constant multiplier. Default value is 1.
    is_random : boolean, default False
        - If True, randomly change brightness.

    References
    -----------
    - `skimage.exposure.adjust_gamma <http://scikit-image.org/docs/dev/api/skimage.exposure.html>`_
    - `chinese blog <http://www.cnblogs.com/denny402/p/5124402.html>`_
    """
    if is_random:
        gamma = np.random.uniform(1-gamma, 1+gamma)
    x = exposure.adjust_gamma(x, gamma, gain)
    return x 
Example #4
Source File: prepro.py    From deepsleepnet with Apache License 2.0 6 votes vote down vote up
def brightness_multi(x, gamma=1, gain=1, is_random=False):
    """Change the brightness of multiply images, randomly or non-randomly.
    Usually be used for image segmentation which x=[X, Y], X and Y should be matched.

    Parameters
    -----------
    x : list of numpy array
        List of images with dimension of [n_images, row, col, channel] (default).
    others : see ``brightness``.
    """
    if is_random:
        gamma = np.random.uniform(1-gamma, 1+gamma)

    results = []
    for data in x:
        results.append( exposure.adjust_gamma(data, gamma, gain) )
    return np.asarray(results)


# contrast 
Example #5
Source File: prepro.py    From deepsleepnet with Apache License 2.0 6 votes vote down vote up
def brightness(x, gamma=1, gain=1, is_random=False):
    """Change the brightness of a single image, randomly or non-randomly.

    Parameters
    -----------
    x : numpy array
        An image with dimension of [row, col, channel] (default).
    gamma : float, small than 1 means brighter.
        Non negative real number. Default value is 1.

        - If is_random is True, gamma in a range of (1-gamma, 1+gamma).
    gain : float
        The constant multiplier. Default value is 1.
    is_random : boolean, default False
        - If True, randomly change brightness.

    References
    -----------
    - `skimage.exposure.adjust_gamma <http://scikit-image.org/docs/dev/api/skimage.exposure.html>`_
    - `chinese blog <http://www.cnblogs.com/denny402/p/5124402.html>`_
    """
    if is_random:
        gamma = np.random.uniform(1-gamma, 1+gamma)
    x = exposure.adjust_gamma(x, gamma, gain)
    return x 
Example #6
Source File: image1.py    From ASR33 with MIT License 6 votes vote down vote up
def load_image(filename, width, invert, gamma):
    # Read the image
    img = imageio.imread(filename)

    if img.shape[-1] == 4:
        # Blend the alpha channel
        img = color.rgba2rgb(img)

    # Grayscale
    img = color.rgb2gray(img)

    # Resample and adjust the aspect ratio
    width_px = (3 * width) * 16

    img_width = 1.0 * width_px
    img_height = int(img.shape[0] * 3 * (img_width / (4 * img.shape[1])))
    img = transform.resize(img, (img_height, img_width), anti_aliasing=True, mode='constant')

    # Adjust the exposure
    img = exposure.adjust_gamma(img, gamma)

    if invert:
        img = 1 - img

    return img 
Example #7
Source File: prepro.py    From LapSRN-tensorflow with Apache License 2.0 6 votes vote down vote up
def brightness(x, gamma=1, gain=1, is_random=False):
    """Change the brightness of a single image, randomly or non-randomly.

    Parameters
    -----------
    x : numpy array
        An image with dimension of [row, col, channel] (default).
    gamma : float, small than 1 means brighter.
        Non negative real number. Default value is 1.

        - If is_random is True, gamma in a range of (1-gamma, 1+gamma).
    gain : float
        The constant multiplier. Default value is 1.
    is_random : boolean, default False
        - If True, randomly change brightness.

    References
    -----------
    - `skimage.exposure.adjust_gamma <http://scikit-image.org/docs/dev/api/skimage.exposure.html>`_
    - `chinese blog <http://www.cnblogs.com/denny402/p/5124402.html>`_
    """
    if is_random:
        gamma = np.random.uniform(1-gamma, 1+gamma)
    x = exposure.adjust_gamma(x, gamma, gain)
    return x 
Example #8
Source File: PredictOneClassifier.py    From kaggle-rsna18 with MIT License 5 votes vote down vote up
def data_augmentation(image):
    # Input should be ONE image with shape: (L, W, CH)
    options = ["gaussian_smooth", "vertical_flip", "rotate", "zoom", "adjust_gamma"] 
    # Probabilities for each augmentation were arbitrarily assigned 
    which_option = np.random.choice(options)
    if which_option == "vertical_flip":
        image = np.fliplr(image)
    if which_option == "horizontal_flip": 
        image = np.flipud(image) 
    elif which_option == "gaussian_smooth": 
        sigma = np.random.uniform(0.2, 1.0)
        image = gaussian_filter(image, sigma)
    elif which_option == "zoom": 
      # Assumes image is square
        min_crop = int(image.shape[0]*0.85)
        max_crop = int(image.shape[0]*0.95)
        crop_size = np.random.randint(min_crop, max_crop) 
        crop = crop_center(image, crop_size, crop_size)
        if crop.shape[-1] == 1: crop = crop[:,:,0]
        image = scipy.misc.imresize(crop, image.shape) 
    elif which_option == "rotate":
        angle = np.random.uniform(-15, 15)
        image = rotate(image, angle, reshape=False)
    elif which_option == "adjust_gamma": 
        image = image / 255. 
        image = exposure.adjust_gamma(image, np.random.uniform(0.75,1.25))
        image = image * 255. 
    if len(image.shape) == 2: image = np.expand_dims(image, axis=2)
    return image 
Example #9
Source File: PredictClassifierEnsemble.py    From kaggle-rsna18 with MIT License 5 votes vote down vote up
def data_augmentation(image):
    # Input should be ONE image with shape: (L, W, CH)
    options = ["gaussian_smooth", "vertical_flip", "rotate", "zoom", "adjust_gamma"] 
    # Probabilities for each augmentation were arbitrarily assigned 
    which_option = np.random.choice(options)
    if which_option == "vertical_flip":
        image = np.fliplr(image)
    if which_option == "horizontal_flip": 
        image = np.flipud(image) 
    elif which_option == "gaussian_smooth": 
        sigma = np.random.uniform(0.2, 1.0)
        image = gaussian_filter(image, sigma)
    elif which_option == "zoom": 
      # Assumes image is square
        min_crop = int(image.shape[0]*0.85)
        max_crop = int(image.shape[0]*0.95)
        crop_size = np.random.randint(min_crop, max_crop) 
        crop = crop_center(image, crop_size, crop_size)
        if crop.shape[-1] == 1: crop = crop[:,:,0]
        image = scipy.misc.imresize(crop, image.shape) 
    elif which_option == "rotate":
        angle = np.random.uniform(-15, 15)
        image = rotate(image, angle, reshape=False)
    elif which_option == "adjust_gamma": 
        image = image / 255. 
        image = exposure.adjust_gamma(image, np.random.uniform(0.75,1.25))
        image = image * 255. 
    if len(image.shape) == 2: image = np.expand_dims(image, axis=2)
    return image 
Example #10
Source File: image2.py    From ASR33 with MIT License 5 votes vote down vote up
def load_image(filename, width, invert, gamma):
    # Read the image
    img = imageio.imread(filename)

    if img.shape[-1] == 4:
        # Blend the alpha channel
        img = color.rgba2rgb(img, background=(0, 0, 0))

    # Grayscale
    img = color.rgb2gray(img)

    # Adjust the exposure
    img = exposure.adjust_gamma(img, gamma)

    if invert:
        img = util.invert(img)

    # Resample and adjust the aspect ratio
    width_px = (3 * width) * CELLPX

    img_width = 1.0 * width_px
    img_height = int(img.shape[0] * 3 * (img_width / (4 * img.shape[1])))
    img = transform.resize(img, (img_height, img_width), anti_aliasing=True, mode='reflect')

    img = (img - img.min()) / (img.max() - img.min())
    return img 
Example #11
Source File: TrainOneClassifier.py    From kaggle-rsna18 with MIT License 5 votes vote down vote up
def data_augmentation(image):
    # Input should be ONE image with shape: (L, W, CH)
    options = ["gaussian_smooth", "rotate", "zoom", "adjust_gamma"]  
    # Probabilities for each augmentation were arbitrarily assigned 
    which_option = np.random.choice(options)
    if which_option == "gaussian_smooth": 
        sigma = np.random.uniform(0.2, 1.0)
        image = gaussian_filter(image, sigma)
    elif which_option == "zoom": 
      # Assumes image is square
        min_crop = int(image.shape[0]*0.85)
        max_crop = int(image.shape[0]*0.95)
        crop_size = np.random.randint(min_crop, max_crop) 
        crop = crop_center(image, crop_size, crop_size)
        if crop.shape[-1] == 1: crop = crop[:,:,0]
        image = scipy.misc.imresize(crop, image.shape) 
    elif which_option == "rotate":
        angle = np.random.uniform(-15, 15)
        image = rotate(image, angle, reshape=False)
    elif which_option == "adjust_gamma": 
        image = image / 255. 
        image = exposure.adjust_gamma(image, np.random.uniform(0.75,1.25))
        image = image * 255. 
    if len(image.shape) == 2: image = np.expand_dims(image, axis=2)
    return image 

# == I/O == # 
Example #12
Source File: TrainClassifierEnsemble.py    From kaggle-rsna18 with MIT License 5 votes vote down vote up
def data_augmentation(image):
    # Input should be ONE image with shape: (L, W, CH)
    options = ["gaussian_smooth", "rotate", "zoom", "adjust_gamma"]  
    # Probabilities for each augmentation were arbitrarily assigned 
    which_option = np.random.choice(options)
    if which_option == "gaussian_smooth": 
        sigma = np.random.uniform(0.2, 1.0)
        image = gaussian_filter(image, sigma)
    elif which_option == "zoom": 
      # Assumes image is square
        min_crop = int(image.shape[0]*0.85)
        max_crop = int(image.shape[0]*0.95)
        crop_size = np.random.randint(min_crop, max_crop) 
        crop = crop_center(image, crop_size, crop_size)
        if crop.shape[-1] == 1: crop = crop[:,:,0]
        image = scipy.misc.imresize(crop, image.shape) 
    elif which_option == "rotate":
        angle = np.random.uniform(-15, 15)
        image = rotate(image, angle, reshape=False)
    elif which_option == "adjust_gamma": 
        image = image / 255. 
        image = exposure.adjust_gamma(image, np.random.uniform(0.75,1.25))
        image = image * 255. 
    if len(image.shape) == 2: image = np.expand_dims(image, axis=2)
    return image 

# == I/O == # 
Example #13
Source File: data_generator.py    From Advanced-Deep-Learning-with-Keras with MIT License 5 votes vote down vote up
def apply_random_exposure_adjust(self, image, percent=30):
        """Apply random exposure adjustment on an image (not used)"""
        random = np.random.randint(0, 100)
        if random < percent:
            image = exposure.adjust_gamma(image, gamma=0.4, gain=0.9)
            # another exposure algo
            # image = exposure.adjust_log(image)
        return image 
Example #14
Source File: image_tfs.py    From tanda with MIT License 5 votes vote down vote up
def TF_adjust_gamma(x, gamma=1.0):
    assert len(x.shape) == 3
    h, w, nc = x.shape
    return adjust_gamma(x, gamma) 
Example #15
Source File: run_BSD.py    From harmonicConvolutions with MIT License 5 votes vote down vote up
def bsd_preprocess(im, tg):
    '''Data normalizations and augmentations'''
    fliplr = (np.random.rand() > 0.5)
    flipud = (np.random.rand() > 0.5)
    gamma = np.minimum(np.maximum(1. + np.random.randn(), 0.5), 1.5)
    if fliplr:
        im = np.fliplr(im)
        tg = np.fliplr(tg)
    if flipud:
        im = np.flipud(im)
        tg = np.flipud(tg)
    im = skiex.adjust_gamma(im, gamma)
    return im, tg 
Example #16
Source File: transforms.py    From KagglePlanetPytorch with MIT License 5 votes vote down vote up
def random_gamma(gamma=lambda: np.random.rand() * 0.4 + 0.8):
    def call(x):
        return exposure.adjust_gamma(x, gamma())

    return call 
Example #17
Source File: data_generator.py    From Silhouette-Guided-3D with MIT License 4 votes vote down vote up
def __getitem__(self, idx):
        pkl_path = os.path.join(self.root_dir,self.namelist[idx])
        pkl = pickle.load(open(pkl_path, 'rb'), encoding='bytes')
        img = pkl[0].astype('float32')/255.0
        label = pkl[1][:,:3]
        
        # re-sample ground truth, ShapeNet point cloud ground truth by Wang et al. is not of the same number across images
        if label.shape[0]<self.refine_size:
            # re-sample
            sub_iter = self.refine_size // label.shape[0]
            sub_num =  self.refine_size - label.shape[0]*sub_iter
            label_n = label.copy()
            for i in range(sub_iter-1):
                label = np.concatenate((label, label_n), axis=0)
            subidx = np.random.permutation(label_n.shape[0])
            subidx = subidx[:sub_num]
            label = np.concatenate((label, label_n[subidx]), axis=0)

        # load mask
        mask_path = self.root_dir+self.namelist[idx][:5]+'mask/'+self.namelist[idx][19:-3]+'png'
        mask = scipy.ndimage.imread(mask_path)
        mask = np.expand_dims(mask,axis=2)

        subidx = np.random.permutation(label.shape[0])
        subidx = subidx[:self.refine_size]
        label_f = label[subidx]
        label_f = np.float32(label_f)

        # data augmentation
        if self.train_type == 'train':
            # gamma
            random.seed()
            g_prob = np.random.random()*1+0.5
            img = exposure.adjust_gamma(img, g_prob)
            # intensity
            random.seed()
            g_prob = np.random.random()*127
            img = exposure.rescale_intensity(img*255.0, in_range=(g_prob, 255))
            # color channel
            random.seed()
            g_prob = np.random.random()*0.4+0.8
            img[:,:,0] = img[:,:,0]*g_prob
            random.seed()
            g_prob = np.random.random()*0.4+0.8
            img[:,:,1] = img[:,:,1]*g_prob
            random.seed()
            g_prob = np.random.random()*0.4+0.8
            img[:,:,2] = img[:,:,2]*g_prob
            np.clip(img, 0.0, 1.0 , out=img)

        # permute dim
        if self.transform:
            if self.train_type == 'train':
                img = data_transforms['train'](img).float()
                mask = data_transforms['train'](mask).float() 
            else:
                img = data_transforms['val'](img).float()
                mask = data_transforms['val'](mask).float()

        return img, label_f,  mask 
Example #18
Source File: Segmentation_Models.py    From brain_segmentation with MIT License 4 votes vote down vote up
def show_segmented_image(self, test_img, modality='t1c', show = False):
        '''
        Creates an image of original brain with segmentation overlay
        INPUT   (1) str 'test_img': filepath to test image for segmentation, including file extension
                (2) str 'modality': imaging modelity to use as background. defaults to t1c. options: (flair, t1, t1c, t2)
                (3) bool 'show': If true, shows output image. defaults to False.
        OUTPUT  (1) if show is True, shows image of segmentation results
                (2) if show is false, returns segmented image.
        '''
        modes = {'flair':0, 't1':1, 't1c':2, 't2':3}

        segmentation = self.predict_image(test_img, show=False)
        img_mask = np.pad(segmentation, (16,16), mode='edge')
        ones = np.argwhere(img_mask == 1)
        twos = np.argwhere(img_mask == 2)
        threes = np.argwhere(img_mask == 3)
        fours = np.argwhere(img_mask == 4)

        test_im = io.imread(test_img)
        test_back = test_im.reshape(5,240,240)[-2]
        # overlay = mark_boundaries(test_back, img_mask)
        gray_img = img_as_float(test_back)

        # adjust gamma of image
        image = adjust_gamma(color.gray2rgb(gray_img), 0.65)
        sliced_image = image.copy()
        red_multiplier = [1, 0.2, 0.2]
        yellow_multiplier = [1,1,0.25]
        green_multiplier = [0.35,0.75,0.25]
        blue_multiplier = [0,0.25,0.9]

        # change colors of segmented classes
        for i in xrange(len(ones)):
            sliced_image[ones[i][0]][ones[i][1]] = red_multiplier
        for i in xrange(len(twos)):
            sliced_image[twos[i][0]][twos[i][1]] = green_multiplier
        for i in xrange(len(threes)):
            sliced_image[threes[i][0]][threes[i][1]] = blue_multiplier
        for i in xrange(len(fours)):
            sliced_image[fours[i][0]][fours[i][1]] = yellow_multiplier

        if show:
            io.imshow(sliced_image)
            plt.show()

        else:
            return sliced_image 
Example #19
Source File: cambridge_dataset.py    From sanet_relocal_demo with GNU General Public License v3.0 4 votes vote down vote up
def load_frame_2_tensors(self, frame, out_frame_dim):
        C, H, W = out_frame_dim

        tag = frame['tag']
        if tag is not None:
            is_neg = True if 'n' in tag else False
        else:
            is_neg = False

        K = K_from_frame(frame)
        Tcw = np.asarray(frame['extrinsic_Tcw'][:3, :], dtype=np.float32).reshape((3, 4))
        Rcw, tcw = Tcw[:3, :3], Tcw[:3, 3]
        img_file_name = frame['file_name']
        depth_file_name = frame['depth_file_name']

        # Load image and depth
        img = cv2.imread(os.path.join(self.cambridge_base_dir, img_file_name))
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB).astype(np.float32) / 255.0
        depth = load_depth_from_tiff((os.path.join(self.cambridge_base_dir, depth_file_name)))
        ori_H, ori_W, _ = img.shape

        # Post-process image and depth (fill the holes with cross bilateral filter)
        img = cv2.resize(img, dsize=(int(W), int(H)))
        if self.random_gamma:
            gamma = np.random.uniform(low=self.random_gamma_thres[0], high=self.random_gamma_thres[1])
            img = adjust_gamma(img, gamma)

        depth = cv2.resize(depth, dsize=(int(W), int(H)), interpolation=cv2.INTER_NEAREST)
        if self.remove_depth_outlier > 0:
            depth = clamp_data_with_ratio(depth, ratio=self.remove_depth_outlier, fill_value=1e-5)
        depth[depth < 1e-5] = 1e-5

        # camera intrinsic parameters:
        K[0, 0] *= (W/ori_W)
        K[0, 2] *= (W/ori_W)
        K[1, 1] *= (H/ori_H)
        K[1, 2] *= (H/ori_H)

        # camera motion representation: (center, rotation_center2world)
        c = camera_center_from_Tcw(Rcw, tcw)
        Rwc = np.eye(4)
        Rwc[:3, :3] = Rcw.T
        q = quaternion_from_matrix(Rwc)
        log_q = log_quat(q)
        pose_vector = np.concatenate((c, log_q)).astype(np.float32)

        # convert to torch.tensor
        ori_img_tensor = torch.from_numpy(img.transpose((2, 0, 1)))  # (C, H, W)
        img_tensor = ori_img_tensor.clone()
        if self.transform_func:
            img_tensor = self.transform_func(img_tensor)
        depth_tensor = torch.from_numpy(depth).view(1, H, W)  # (1, H, W)
        pose_vector = torch.from_numpy(pose_vector)           # (1, 3)
        Tcw_tensor = torch.from_numpy(Tcw)                    # (3, 4)
        K_tensor = torch.from_numpy(K)                        # (3, 3)
        neg_tensor = torch.from_numpy(np.asarray([1], dtype=np.int32)) if is_neg is True else \
            torch.from_numpy(np.asarray([0], dtype=np.int32))

        return pose_vector, img_tensor, depth_tensor, K_tensor, Tcw_tensor, ori_img_tensor, neg_tensor