Change image contrast in PIL

I have a program that should change the contrast, but I feel that it does not change the contrast. She changes some areas to red, while I do not want this. If you could tell me how to remove them, thanks. 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

+4
source share
2 answers

I could not reproduce your error. On my platform (debian), only the Pillow plug is available, so if you are using the old PIL package, this may be the reason.

Image.point() . , , 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

: (). , . level 259, . - , , .

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

, , [0-255], , , , - .

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)
+9

PIL contrast. .

from PIL import Image, ImageEnhance
image = Image.open(':\\Users\\omar\\Desktop\\Site\\Images\\obama.png')
scale_value=scale1.get()
contrast = ImageEnhance.Contrast(image)
contrast_applied=contrast.enhance(scale_value)
image.show()
+4

Source: https://habr.com/ru/post/1668831/


All Articles