Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change contrast of image in PIL

I have a program that's supposed to change the contrast, but I feel like it's not really changing the contrast.It changes some areas to red whereas I don't want it to. If you could tell me how to remove them, thank you. Here is the code:

from PIL import Image


def change_contrast(img, level):

    img = Image.open("C:\\Users\\omar\\Desktop\\Site\\Images\\obama.png")
    img.load()

    factor = (259 * (level+255)) / (255 * (259-level))
    for x in range(img.size[0]):
        for y in range(img.size[1]):
            color = img.getpixel((x, y))
            new_color = tuple(int(factor * (c-128) + 128) for c in color)
            img.putpixel((x, y), new_color)

    return img

result = change_contrast('C:\\Users\\omar\\Desktop\\Site\\Images\\test_image1.jpg', 100)
result.save('C:\\Users\\omar\\Desktop\\Site\\Images\\test_image1_output.jpg')
print('done')

And here is the image and its result:

obama.png obama modified

If this is the actual contrast method, feel free to tell me

like image 536
Megzari Nassim Avatar asked Feb 04 '17 20:02

Megzari Nassim


1 Answers

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.

def change_contrast(img, level):
    factor = (259 * (level + 255)) / (255 * (259 - level))
    def contrast(c):
        return 128 + factor * (c - 128)
    return img.point(contrast)

change_contrast(Image.open('barry.png'), 100)

output

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])

another output

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.

def change_contrast(img, level):
    factor = (259 * (level + 255)) / (255 * (259 - level))
    def contrast(c):
        value = 128 + factor * (c - 128)
        return max(0, min(255, value))
    return img.point(contrast)
like image 70
Håken Lid Avatar answered Sep 24 '22 08:09

Håken Lid