Channel mix with Pillow

前端 未结 2 1032
被撕碎了的回忆
被撕碎了的回忆 2021-01-19 17:18

I would like to do some color transformations, for example given RGB channels

R =  G + B / 2

or some other transformation where a channel v

2条回答
  •  深忆病人
    2021-01-19 17:39

    For this particular operation, the color transformation can be written as a matrix multiplication, so you could use the convert() method with a custom matrix (assuming no alpha channel):

    # img must be in RGB mode (not RGBA):
    transformed_img = img.convert('RGB', (
        0, 1, .5, 0,
        0, 1, 0, 0,
        0, 0, 1, 0,
    ))
    

    Otherwise, you can split() the image into 3 or 4 images of each color band, apply whatever operation you like, and finally merge() those bands back to a single image. Again, the original image should be in RGB or RGBA mode.

    (red, green, blue, *rest) = img.split()
    half_blue = PIL.ImageChops.multiply(blue, PIL.ImageChops.constant(blue, 128))
    new_red = PIL.ImageChops.add(green, half_blue)
    transformed_img = PIL.Image.merge(img.mode, (new_red, green, blue, *rest))
    

提交回复
热议问题