python PIL:调整色调和饱和度

2 投票
2 回答
6838 浏览
提问于 2025-04-18 14:10

在GIMP这个软件里,我可以很简单地调整图片的色调和饱和度。比如,下面是原始图片和经过调整后,色调设置为-90,饱和度设置为100的最终效果。

我该如何在Python的PIL库中实现相同的效果呢?

原始图片

原始图片

最终图片

最终图片

2 个回答

3

你可以通过结合使用 colorsys 模块和 PIL 来实现这个功能,不过速度有点慢。colorsys 让你可以把颜色空间转换为 HSV,这样就很容易调整色调和饱和度。我把饱和度的值提高到 0.65 的幂,这样可以更接近你的例子,同时保持 colorsys 所需的 0.0 到 1.0 的范围,并且增加了中间值的效果。

import colorsys
from PIL import Image
im = Image.open(filename)
ld = im.load()
width, height = im.size
for y in range(height):
    for x in range(width):
        r,g,b = ld[x,y]
        h,s,v = colorsys.rgb_to_hsv(r/255., g/255., b/255.)
        h = (h + -90.0/360.0) % 1.0
        s = s**0.65
        r,g,b = colorsys.hsv_to_rgb(h, s, v)
        ld[x,y] = (int(r * 255.9999), int(g * 255.9999), int(b * 255.9999))

enter image description here

3

我建议你把你的图片转换成一个 numpy 数组,然后使用 matplotlib 的 rgb_to_hsv 函数: http://matplotlib.org/api/colors_api.html#matplotlib.colors.rgb_to_hsv。这样做可以避免使用双重循环,这样可能会导致用 colorsys 逐个像素处理时变得很慢。

撰写回答