如何实现PIL着色功能?

时间:2019-06-26 19:01:41

标签: scikit-image

使用PIL,我可以先将图像转换为灰度,然后再应用colorize转换来转换图像的颜色。有办法对scikit-image进行同样的处理吗?

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

1 个答案:

答案 0 :(得分:2)

我认为您希望这样避免对PIL /枕头的依赖:

#!/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')

那会变成这样:

enter image description here

对此:

enter image description here


请注意,这等效于 ImageMagick -level-colors BLACK,WHITE运算符,您可以在 Terminal 中像这样操作:

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

将其转换为

enter image description here

对此:

enter image description here


关键字:Python,PIL,Pillow,图像,图像处理,colorize,colorise,colourise,colorize,level color,skimage,scikit-image。