如何实现 PIL 着色功能?

How can I achieve PIL colorize functionality?

使用 PIL,我可以通过首先将图像转换为灰度然后应用着色变换来变换图像的颜色。有没有办法对 scikit-image 做同样的事情?

与例如Color rotation in HSV using scikit-image 的问题是在 PIL 着色函数中黑色保持黑色,我可以定义我想要将黑色和白色映射到的位置。

我想你想要这样的东西来避免对 PIL/Pillow:

的任何依赖
#!/usr/bin/env python3

import numpy as np
from PIL import Image

def colorize(im,black,white):
    """Do equivalent of PIL's "colorize()" function"""
    # Pick up low and high end of the ranges for R, G and B
    Rlo, Glo, Blo = black
    Rhi, Ghi, Bhi = white

    # Make new, empty Red, Green and Blue channels which we'll fill & merge to RGB later
    R = np.zeros(im.shape, dtype=np.float)
    G = np.zeros(im.shape, dtype=np.float)
    B = np.zeros(im.shape, dtype=np.float)

    R = im/255 * (Rhi-Rlo) + Rlo
    G = im/255 * (Ghi-Glo) + Glo
    B = im/255 * (Bhi-Blo) + Blo

    return (np.dstack((R,G,B))).astype(np.uint8)


# Create black-white left-right gradient image, 256 pixels wide and 100 pixels tall
grad = np.repeat(np.arange(256,dtype=np.uint8).reshape(1,-1), 100, axis=0) 
Image.fromarray(grad).save('start.png')

# Colorize from green to magenta
result = colorize(grad, [0,255,0], [255,0,255])

# Save result - using PIL because I don't know skimage that well
Image.fromarray(result).save('result.png')

这会变成这样:

进入这个:


请注意,这相当于 ImageMagick-level-colors BLACK,WHITE 运算符,您可以在 Terminal 中执行此操作,如下所示:

convert input.png -level-colors lime,magenta result.png

转换为:

进入这个:


关键词: Python, PIL, Pillow, image, image processing, colorize, colorise, colourise, colourize, level colors, skimage, scikit-image .