Change Contrast Of Image In Pil
Solution 1:
I couldn't reproduce your bug. On my platform (debian) only the Pillow fork is available, so if you are using the older PIL package, that might be the cause.
In any case, there's a built in method Image.point()
for doing this kind of operation. It will map over each pixel in each channel, which should be faster than doing three nested loops in python.
defchange_contrast(img, level):
factor = (259 * (level + 255)) / (255 * (259 - level))
defcontrast(c):
return128 + factor * (c - 128)
return img.point(contrast)
change_contrast(Image.open('barry.png'), 100)
Your output looks like you have a overflow in a single channel (red). I don't see any reason why that would happen. But if your level
is higher than 259, the output is inverted. Something like that is probably the cause of the initial bug.
def change_contrast_multi(img, steps):
width, height = img.size
canvas = Image.new('RGB', (width * len(steps), height))
for n, level in enumerate(steps):
img_filtered = change_contrast(img, level)
canvas.paste(img_filtered, (width * n, 0))
return canvas
change_contrast_multi(Image.open('barry.png'), [-100, 0, 100, 200, 300])
A possible fix is to make sure the contrast filter only return values within the range [0-255], since the bug seems be caused by negative values overflowing somehow.
defchange_contrast(img, level):
factor = (259 * (level + 255)) / (255 * (259 - level))
defcontrast(c):
value = 128 + factor * (c - 128)
returnmax(0, min(255, value))
return img.point(contrast)
Solution 2:
There's already built a class called contrast in PIL module. You can simply use it.
from PIL import Image, ImageEnhance
image = Image.open(':\\Users\\omar\\Desktop\\Site\\Images\\obama.png')
scale_value=scale1.get()
image = ImageEnhance.Contrast(image).enhance(scale_value)
image.show()
Post a Comment for "Change Contrast Of Image In Pil"