Python PIL.ImageEnhance.Brightness() Examples

The following are 30 code examples of PIL.ImageEnhance.Brightness(). 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 PIL.ImageEnhance , or try the search function .
Example #1
Source File: transforms_tools.py    From deep-image-retrieval with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def adjust_brightness(img, brightness_factor):
    """Adjust brightness of an Image.
    Args:
    img (PIL Image): PIL Image to be adjusted.
    brightness_factor (float):  How much to adjust the brightness. Can be
    any non negative number. 0 gives a black image, 1 gives the
    original image while 2 increases the brightness by a factor of 2.
    Returns:
    PIL Image: Brightness adjusted image.
    """
    if not is_pil_image(img):
        raise TypeError('img should be PIL Image. Got {}'.format(type(img)))

    enhancer = ImageEnhance.Brightness(img)
    img = enhancer.enhance(brightness_factor)
    return img 
Example #2
Source File: lomolive.py    From wx-fancy-pic with MIT License 6 votes vote down vote up
def lomoize (image,darkness,saturation):
	
	(width,height) = image.size

	max = width
	if height > width:
		max = height
	
	mask = Image.open("./lomolive/lomomask.jpg").resize((max,max))

	left = round((max - width) / 2)
	upper = round((max - height) / 2)
	
	mask = mask.crop((left,upper,left+width,upper + height))

#	mask = Image.open('mask_l.png')

	darker = ImageEnhance.Brightness(image).enhance(darkness)	
	saturated = ImageEnhance.Color(image).enhance(saturation)
	lomoized = Image.composite(saturated,darker,mask)
	
	return lomoized 
Example #3
Source File: generator.py    From VerifAI with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def modifyImageBscc(imageData, brightness, sharpness, contrast, color):
    """Update with brightness, sharpness, contrast and color."""

    brightnessMod = ImageEnhance.Brightness(imageData)
    imageData = brightnessMod.enhance(brightness)

    sharpnessMod = ImageEnhance.Sharpness(imageData)
    imageData = sharpnessMod.enhance(sharpness)

    contrastMod = ImageEnhance.Contrast(imageData)
    imageData = contrastMod.enhance(contrast)

    colorMod = ImageEnhance.Color(imageData)
    imageData = colorMod.enhance(color)

    return imageData 
Example #4
Source File: functional.py    From ACoL with MIT License 6 votes vote down vote up
def adjust_brightness(img, brightness_factor):
    """Adjust brightness of an Image.

    Args:
        img (PIL Image): PIL Image to be adjusted.
        brightness_factor (float):  How much to adjust the brightness. Can be
            any non negative number. 0 gives a black image, 1 gives the
            original image while 2 increases the brightness by a factor of 2.

    Returns:
        PIL Image: Brightness adjusted image.
    """
    if not _is_pil_image(img):
        raise TypeError('img should be PIL Image. Got {}'.format(type(img)))

    enhancer = ImageEnhance.Brightness(img)
    img = enhancer.enhance(brightness_factor)
    return img 
Example #5
Source File: functional.py    From Global-Second-order-Pooling-Convolutional-Networks with MIT License 6 votes vote down vote up
def adjust_brightness(img, brightness_factor):
    """Adjust brightness of an Image.

    Args:
        img (PIL Image): PIL Image to be adjusted.
        brightness_factor (float):  How much to adjust the brightness. Can be
            any non negative number. 0 gives a black image, 1 gives the
            original image while 2 increases the brightness by a factor of 2.

    Returns:
        PIL Image: Brightness adjusted image.
    """
    if not _is_pil_image(img):
        raise TypeError('img should be PIL Image. Got {}'.format(type(img)))

    enhancer = ImageEnhance.Brightness(img)
    img = enhancer.enhance(brightness_factor)
    return img 
Example #6
Source File: CuteR.py    From CuteR with GNU General Public License v3.0 6 votes vote down vote up
def produce(txt,img,ver=5,err_crt = qrcode.constants.ERROR_CORRECT_H,bri = 1.0, cont = 1.0,\
        colourful = False, rgba = (0,0,0,255),pixelate = False):
    """Produce QR code

    :txt: QR text
    :img: Image path / Image object
    :ver: QR version
    :err_crt: QR error correct
    :bri: Brightness enhance
    :cont: Contrast enhance
    :colourful: If colourful mode
    :rgba: color to replace black
    :pixelate: pixelate
    :returns: list of produced image

    """
    if type(img) is Image.Image:
        pass
    elif type(img) is str:
        img = Image.open(img)
    else:
        return []
    frames = [produce_impl(txt,frame.copy(),ver,err_crt,bri,cont,colourful,rgba,pixelate) for frame in ImageSequence.Iterator(img)]
    return frames 
Example #7
Source File: functional.py    From SPG with MIT License 6 votes vote down vote up
def adjust_brightness(img, brightness_factor):
    """Adjust brightness of an Image.

    Args:
        img (PIL Image): PIL Image to be adjusted.
        brightness_factor (float):  How much to adjust the brightness. Can be
            any non negative number. 0 gives a black image, 1 gives the
            original image while 2 increases the brightness by a factor of 2.

    Returns:
        PIL Image: Brightness adjusted image.
    """
    if not _is_pil_image(img):
        raise TypeError('img should be PIL Image. Got {}'.format(type(img)))

    enhancer = ImageEnhance.Brightness(img)
    img = enhancer.enhance(brightness_factor)
    return img 
Example #8
Source File: transforms.py    From ACAN with MIT License 6 votes vote down vote up
def adjust_brightness(img, brightness_factor):
    """Adjust brightness of an Image.

    Args:
        img (PIL Image): PIL Image to be adjusted.
        brightness_factor (float):  How much to adjust the brightness. Can be
            any non negative number. 0 gives a black image, 1 gives the
            original image while 2 increases the brightness by a factor of 2.

    Returns:
        PIL Image: Brightness adjusted image.
    """
    if not _is_pil_image(img):
        raise TypeError('img should be PIL Image. Got {}'.format(type(img)))

    enhancer = ImageEnhance.Brightness(img)
    img = enhancer.enhance(brightness_factor)
    return img 
Example #9
Source File: functional.py    From Deep-Exemplar-based-Colorization with MIT License 6 votes vote down vote up
def adjust_brightness(img, brightness_factor):
    """Adjust brightness of an Image.

    Args:
        img (PIL Image): PIL Image to be adjusted.
        brightness_factor (float):  How much to adjust the brightness. Can be
            any non negative number. 0 gives a black image, 1 gives the
            original image while 2 increases the brightness by a factor of 2.

    Returns:
        PIL Image: Brightness adjusted image.
    """
    if not _is_pil_image(img):
        raise TypeError('img should be PIL Image. Got {}'.format(type(img)))

    enhancer = ImageEnhance.Brightness(img)
    img = enhancer.enhance(brightness_factor)
    return img 
Example #10
Source File: neural_style_transfer.py    From Style_Migration_For_Artistic_Font_With_CNN with MIT License 6 votes vote down vote up
def save_img(fname, image, image_enhance=False):  # 图像可以增强
    image = Image.fromarray(image)
    if image_enhance:
        # 亮度增强
        enh_bri = ImageEnhance.Brightness(image)
        brightness = 1.2
        image = enh_bri.enhance(brightness)

        # 色度增强
        enh_col = ImageEnhance.Color(image)
        color = 1.2
        image = enh_col.enhance(color)

        # 锐度增强
        enh_sha = ImageEnhance.Sharpness(image)
        sharpness = 1.2
        image = enh_sha.enhance(sharpness)
    imsave(fname, image)
    return 
Example #11
Source File: transforms.py    From self-supervised-depth-completion with MIT License 6 votes vote down vote up
def adjust_brightness(img, brightness_factor):
    """Adjust brightness of an Image.

    Args:
        img (PIL Image): PIL Image to be adjusted.
        brightness_factor (float):  How much to adjust the brightness. Can be
            any non negative number. 0 gives a black image, 1 gives the
            original image while 2 increases the brightness by a factor of 2.

    Returns:
        PIL Image: Brightness adjusted image.
    """
    if not _is_pil_image(img):
        raise TypeError('img should be PIL Image. Got {}'.format(type(img)))

    enhancer = ImageEnhance.Brightness(img)
    img = enhancer.enhance(brightness_factor)
    return img 
Example #12
Source File: extractor.py    From imago-forensics with MIT License 6 votes vote down vote up
def ela(filename, output_path):
    print "****ELA is in BETA****"
    if magic.from_file(filename, mime=True) == "image/jpeg":
        quality_level = 85
        tmp_img = os.path.join(output_path,os.path.basename(filename)+".tmp.jpg")
        ela = os.path.join(output_path,os.path.basename(filename)+".ela.jpg")
        image = Image.open(filename)
        image.save(tmp_img, 'JPEG', quality=quality_level)
        tmp_img_file = Image.open(tmp_img)
        ela_image = ImageChops.difference(image, tmp_img_file)
        extrema = ela_image.getextrema()
        max_diff = max([ex[1] for ex in extrema])
        scale = 255.0/max_diff
        ela_image = ImageEnhance.Brightness(ela_image).enhance(scale)
        ela_image.save(ela)
        os.remove(tmp_img)
    else:
        print "ELA works only with JPEG"


#Modified version of a gist by: https://github.com/erans 
Example #13
Source File: datasets.py    From ICIAR2018 with MIT License 6 votes vote down vote up
def __getitem__(self, index):
        im, xpatch, ypatch, rotation, flip, enhance = np.unravel_index(index, self.shape)

        with Image.open(self.names[im]) as img:
            extractor = PatchExtractor(img=img, patch_size=PATCH_SIZE, stride=self.stride)
            patch = extractor.extract_patch((xpatch, ypatch))

            if rotation != 0:
                patch = patch.rotate(rotation * 90)

            if flip != 0:
                patch = patch.transpose(Image.FLIP_LEFT_RIGHT)

            if enhance != 0:
                factors = np.random.uniform(.5, 1.5, 3)
                patch = ImageEnhance.Color(patch).enhance(factors[0])
                patch = ImageEnhance.Contrast(patch).enhance(factors[1])
                patch = ImageEnhance.Brightness(patch).enhance(factors[2])

            label = self.labels[self.names[im]]
            return transforms.ToTensor()(patch), label 
Example #14
Source File: image.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def apply_brightness_shift(x, brightness):
    """Performs a brightness shift.

    # Arguments
        x: Input tensor. Must be 3D.
        brightness: Float. The new brightness value.
        channel_axis: Index of axis for channels in the input tensor.

    # Returns
        Numpy image tensor.

    # Raises
        ValueError if `brightness_range` isn't a tuple.
    """
    if ImageEnhance is None:
        raise ImportError('Using brightness shifts requires PIL. '
                          'Install PIL or Pillow.')
    x = array_to_img(x)
    x = imgenhancer_Brightness = ImageEnhance.Brightness(x)
    x = imgenhancer_Brightness.enhance(brightness)
    x = img_to_array(x)
    return x 
Example #15
Source File: transform.py    From SegAN with MIT License 6 votes vote down vote up
def adjust_brightness(img, brightness_factor):
    """Adjust brightness of an Image.
    Args:
        img (PIL.Image): PIL Image to be adjusted.
        brightness_factor (float):  How much to adjust the brightness. Can be
            any non negative number. 0 gives a black image, 1 gives the
            original image while 2 increases the brightness by a factor of 2.
    Returns:
        PIL.Image: Brightness adjusted image.
    """
    if not _is_pil_image(img):
        raise TypeError('img should be PIL Image. Got {}'.format(type(img)))

    enhancer = ImageEnhance.Brightness(img)
    img = enhancer.enhance(brightness_factor)
    return img 
Example #16
Source File: image.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
def random_brightness(x, brightness_range):
    """Perform a random brightness shift.

    # Arguments
        x: Input tensor. Must be 3D.
        brightness_range: Tuple of floats; brightness range.
        channel_axis: Index of axis for channels in the input tensor.

    # Returns
        Numpy image tensor.

    # Raises
        ValueError if `brightness_range` isn't a tuple.

    """
    if len(brightness_range) != 2:
        raise ValueError('`brightness_range should be tuple or list of two floats. '
                         'Received arg: ', brightness_range)

    x = array_to_img(x)
    x = imgenhancer_Brightness = ImageEnhance.Brightness(x)
    u = np.random.uniform(brightness_range[0], brightness_range[1])
    x = imgenhancer_Brightness.enhance(u)
    x = img_to_array(x)
    return x 
Example #17
Source File: image.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
def random_brightness(x, brightness_range):
    """Perform a random brightness shift.

    # Arguments
        x: Input tensor. Must be 3D.
        brightness_range: Tuple of floats; brightness range.
        channel_axis: Index of axis for channels in the input tensor.

    # Returns
        Numpy image tensor.

    # Raises
        ValueError if `brightness_range` isn't a tuple.

    """
    if len(brightness_range) != 2:
        raise ValueError('`brightness_range should be tuple or list of two floats. '
                         'Received arg: ', brightness_range)

    x = array_to_img(x)
    x = imgenhancer_Brightness = ImageEnhance.Brightness(x)
    u = np.random.uniform(brightness_range[0], brightness_range[1])
    x = imgenhancer_Brightness.enhance(u)
    x = img_to_array(x)
    return x 
Example #18
Source File: image.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
def random_brightness(x, brightness_range):
    """Perform a random brightness shift.

    # Arguments
        x: Input tensor. Must be 3D.
        brightness_range: Tuple of floats; brightness range.
        channel_axis: Index of axis for channels in the input tensor.

    # Returns
        Numpy image tensor.

    # Raises
        ValueError if `brightness_range` isn't a tuple.

    """
    if len(brightness_range) != 2:
        raise ValueError('`brightness_range should be tuple or list of two floats. '
                         'Received arg: ', brightness_range)

    x = array_to_img(x)
    x = imgenhancer_Brightness = ImageEnhance.Brightness(x)
    u = np.random.uniform(brightness_range[0], brightness_range[1])
    x = imgenhancer_Brightness.enhance(u)
    x = img_to_array(x)
    return x 
Example #19
Source File: gui.py    From superpaper with MIT License 6 votes vote down vote up
def resize_and_bitmap(self, fname, size, enhance_color=False):
        """Take filename of an image and resize and center crop it to size."""
        try:
            pil = resize_to_fill(Image.open(fname), size, quality="fast")
        except UnidentifiedImageError:
            msg = ("Opening image '%s' failed with PIL.UnidentifiedImageError."
                   "It could be corrupted or is of foreign type.") % fname
            sp_logging.G_LOGGER.info(msg)
            # show_message_dialog(msg)
            black_bmp = wx.Bitmap.FromRGBA(size[0], size[1], red=0, green=0, blue=0, alpha=255)
            if enhance_color:
                return (black_bmp, black_bmp)
            return black_bmp
        img = wx.Image(pil.size[0], pil.size[1])
        img.SetData(pil.convert("RGB").tobytes())
        if enhance_color:
            converter = ImageEnhance.Color(pil)
            pilenh_bw = converter.enhance(0.25)
            brightns = ImageEnhance.Brightness(pilenh_bw)
            pilenh = brightns.enhance(0.45)
            imgenh = wx.Image(pil.size[0], pil.size[1])
            imgenh.SetData(pilenh.convert("RGB").tobytes())
            return (img.ConvertToBitmap(), imgenh.ConvertToBitmap())
        return img.ConvertToBitmap() 
Example #20
Source File: image.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
def random_brightness(x, brightness_range):
    """Perform a random brightness shift.

    # Arguments
        x: Input tensor. Must be 3D.
        brightness_range: Tuple of floats; brightness range.
        channel_axis: Index of axis for channels in the input tensor.

    # Returns
        Numpy image tensor.

    # Raises
        ValueError if `brightness_range` isn't a tuple.

    """
    if len(brightness_range) != 2:
        raise ValueError('`brightness_range should be tuple or list of two floats. '
                         'Received arg: ', brightness_range)

    x = array_to_img(x)
    x = imgenhancer_Brightness = ImageEnhance.Brightness(x)
    u = np.random.uniform(brightness_range[0], brightness_range[1])
    x = imgenhancer_Brightness.enhance(u)
    x = img_to_array(x)
    return x 
Example #21
Source File: image.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
def random_brightness(x, brightness_range):
    """Perform a random brightness shift.

    # Arguments
        x: Input tensor. Must be 3D.
        brightness_range: Tuple of floats; brightness range.
        channel_axis: Index of axis for channels in the input tensor.

    # Returns
        Numpy image tensor.

    # Raises
        ValueError if `brightness_range` isn't a tuple.

    """
    if len(brightness_range) != 2:
        raise ValueError('`brightness_range should be tuple or list of two floats. '
                         'Received arg: ', brightness_range)

    x = array_to_img(x)
    x = imgenhancer_Brightness = ImageEnhance.Brightness(x)
    u = np.random.uniform(brightness_range[0], brightness_range[1])
    x = imgenhancer_Brightness.enhance(u)
    x = img_to_array(x)
    return x 
Example #22
Source File: image.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
def random_brightness(x, brightness_range):
    """Perform a random brightness shift.

    # Arguments
        x: Input tensor. Must be 3D.
        brightness_range: Tuple of floats; brightness range.
        channel_axis: Index of axis for channels in the input tensor.

    # Returns
        Numpy image tensor.

    # Raises
        ValueError if `brightness_range` isn't a tuple.

    """
    if len(brightness_range) != 2:
        raise ValueError('`brightness_range should be tuple or list of two floats. '
                         'Received arg: ', brightness_range)

    x = array_to_img(x)
    x = imgenhancer_Brightness = ImageEnhance.Brightness(x)
    u = np.random.uniform(brightness_range[0], brightness_range[1])
    x = imgenhancer_Brightness.enhance(u)
    x = img_to_array(x)
    return x 
Example #23
Source File: image_functions.py    From MAX-Framework with Apache License 2.0 6 votes vote down vote up
def adjust_brightness(img, brightness_factor):
    """Adjust brightness of an Image.

    Args:
        img (PIL Image): PIL Image to be adjusted.
        brightness_factor (float):  How much to adjust the brightness. Can be
            any non negative number. 0 gives a black image, 1 gives the
            original image while 2 increases the brightness by a factor of 2.

    Returns:
        PIL Image: Brightness adjusted image.
    """
    if not _is_pil_image(img):
        raise TypeError('img should be PIL Image. Got {}'.format(type(img)))

    enhancer = ImageEnhance.Brightness(img)
    img = enhancer.enhance(brightness_factor)
    return img 
Example #24
Source File: deepfry.py    From FlameCogs with MIT License 6 votes vote down vote up
def _fry(img):
		e = ImageEnhance.Sharpness(img)
		img = e.enhance(100)
		e = ImageEnhance.Contrast(img)
		img = e.enhance(100)
		e = ImageEnhance.Brightness(img)
		img = e.enhance(.27)
		r, b, g = img.split()
		e = ImageEnhance.Brightness(r)
		r = e.enhance(4)
		e = ImageEnhance.Brightness(g)
		g = e.enhance(1.75)
		e = ImageEnhance.Brightness(b)
		b = e.enhance(.6)
		img = Image.merge('RGB', (r, g, b))
		e = ImageEnhance.Brightness(img)
		img = e.enhance(1.5)
		temp = BytesIO()
		temp.name = 'deepfried.png'
		img.save(temp)
		temp.seek(0)
		return temp 
Example #25
Source File: image.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
def random_brightness(x, brightness_range):
    """Perform a random brightness shift.

    # Arguments
        x: Input tensor. Must be 3D.
        brightness_range: Tuple of floats; brightness range.
        channel_axis: Index of axis for channels in the input tensor.

    # Returns
        Numpy image tensor.

    # Raises
        ValueError if `brightness_range` isn't a tuple.

    """
    if len(brightness_range) != 2:
        raise ValueError('`brightness_range should be tuple or list of two floats. '
                         'Received arg: ', brightness_range)

    x = array_to_img(x)
    x = imgenhancer_Brightness = ImageEnhance.Brightness(x)
    u = np.random.uniform(brightness_range[0], brightness_range[1])
    x = imgenhancer_Brightness.enhance(u)
    x = img_to_array(x)
    return x 
Example #26
Source File: multimedia.py    From chepy with GNU General Public License v3.0 6 votes vote down vote up
def image_brightness(self, factor: int, extension: str = "png"):
        """Change image brightness
        
        Args:
            factor (int): Factor to increase the brightness by
            extension (str, optional): File extension of loaded image. Defaults to "png"
        
        Returns:
            Chepy: The Chepy object. 
        """
        image = Image.open(self._load_as_file())
        image = self._force_rgb(image)
        fh = io.BytesIO()
        enhanced = ImageEnhance.Brightness(image).enhance(factor)
        enhanced.save(fh, extension)
        self.state = fh.getvalue()
        return self 
Example #27
Source File: functional.py    From fast-reid with Apache License 2.0 5 votes vote down vote up
def brightness(pil_img, level, *args):
    level = float_parameter(sample_level(level), 1.8) + 0.1
    return ImageEnhance.Brightness(pil_img).enhance(level)


# operation that overlaps with ImageNet-C's test set 
Example #28
Source File: datasets.py    From ICIAR2018 with MIT License 5 votes vote down vote up
def __getitem__(self, index):
        im, rotation, flip, enhance = np.unravel_index(index, self.shape)

        with Image.open(self.names[im]) as img:

            if flip != 0:
                img = img.transpose(Image.FLIP_LEFT_RIGHT)

            if rotation != 0:
                img = img.rotate(rotation * 90)

            if enhance != 0:
                factors = np.random.uniform(.5, 1.5, 3)
                img = ImageEnhance.Color(img).enhance(factors[0])
                img = ImageEnhance.Contrast(img).enhance(factors[1])
                img = ImageEnhance.Brightness(img).enhance(factors[2])

            extractor = PatchExtractor(img=img, patch_size=PATCH_SIZE, stride=self.stride)
            patches = extractor.extract_patches()

            label = self.labels[self.names[im]]

            b = torch.zeros((len(patches), 3, PATCH_SIZE, PATCH_SIZE))
            for i in range(len(patches)):
                b[i] = transforms.ToTensor()(patches[i])

            return b, label 
Example #29
Source File: drawTriangles.py    From Delaunay_Triangulation with ISC License 5 votes vote down vote up
def brightenImage(im, value):
    enhancer = ImageEnhance.Brightness(im)
    im = enhancer.enhance(value)
    return im 
Example #30
Source File: trans.py    From ocr.pytorch with MIT License 5 votes vote down vote up
def tranfun(self, image):
        image = getpilimage(image)
        bri = ImageEnhance.Brightness(image)
        return bri.enhance(random.uniform(self.lower, self.upper))