首页 > 解决方案 > 将灰度图像转换为彩色 RGBA

问题描述

我有一个背景图像和一个灰度图像,都是 PNG 格式。我想转换灰度图像,使白色变成不同的任意颜色,每个像素的“黑度”变得像一个 alpha/透明通道。然后我想把它放在背景图像的顶部。

我有以下代码:

from PIL import Image

# load images
image = Image.open("image.png")
mask = Image.open("mask.png")

# stretch mask to fit image
mask = mask.resize(image.size)

# get the color of a pixel in the middle of the image to use as mask color
color = image.getpixel((500, 500))

# colorize the greyscale mask to that color, with the "blackness" of each pixel becoming the alpha channel
greyscale_to_color_with_alpha(mask, color)

# apply mask on top of image
image.paste(mask)

def greyscale_to_color_with_alpha(image, color):
    raise NotImplementedError

PIL 被标记是因为这是我目前使用的,但也欢迎使用其他图像库的答案。

标签: pythonpython-3.ximage-processingpython-imaging-library

解决方案


推荐阅读