Python:想像photoshop一样改变图像HSL

时间:2012-12-26 23:45:26

标签: image-processing python-imaging-library

我想在Python中实现这个功能(用滴定的颜色改变HSL),最好使用PIL或者numpy。

enter image description here

有人可以解释这是如何工作的吗?

据我所知,使用内置函数color_to_hsl来获取hsl值,更改它,然后将ti转换回rgb,最后写入单个像素。

任何使它更接近的线索?

2 个答案:

答案 0 :(得分:1)

from PIL import Image
import colorsys

def colorize(im, h, s, l_adjust):
    h /= 360.0
    s /= 100.0
    l_adjust /= 100.0
    if im.mode != 'L':
        im = im.convert('L')
    result = Image.new('RGB', im.size)
    pixin = im.load()
    pixout = result.load()
    for y in range(im.size[1]):
        for x in range(im.size[0]):
            l = pixin[x, y] / 255.99
            l += l_adjust
            l = min(max(l, 0.0), 1.0)
            r, g, b = colorsys.hls_to_rgb(h, l, s)
            r, g, b = int(r * 255.99), int(g * 255.99), int(b * 255.99)
            pixout[x, y] = (r, g, b)
    return result

Original Colorized

答案 1 :(得分:0)

这就是您在photoshop中使用colorize check所做的确切操作

from PIL import Image
import colorsys

def rgbLuminance(r, g, b):
    luminanceR = 0.22248840
    luminanceG = 0.71690369
    luminanceB = 0.06060791
    return (r * luminanceR) + (g * luminanceG) + (b * luminanceB)


def colorize(im, h, s, l_adjust):
    h /= 360.0
    s /= 100.0
    l_adjust /= 100.0
    result = Image.new('RGBA', im.size)
    pixin = im.load()
    pixout = result.load()
    for y in range(im.size[1]):
        for x in range(im.size[0]):
            currentR = pixin[x, y][0]/255
            currentG = pixin[x, y][1]/255
            currentB = pixin[x, y][2]/255
            lum = rgbLuminance(currentR, currentG, currentB)
            if l_adjust > 0:
                lum = lum * (1 - l_adjust)
                lum = lum + (1.0 - (1.0 - l_adjust))
            else:
                lum = lum * (l_adjust + 1)
            l = lum
            r, g, b = colorsys.hls_to_rgb(h, l, s)
            r, g, b = int(r * 255.99), int(g * 255.99), int(b * 255.99)
            pixout[x, y] = (r, g, b, 255)
    return result