python 更改图片对比度,更改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:

j5UID.png

3b8480a566af597730f4544f9893d4c7.png

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

解决方案

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)

d136a4a774ce171859e191f8bb978b3f.png

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

d3e8b9a7aa5156f1150c99ea85864508.png

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值