在像素级别更改文本的背景

问题描述 投票:0回答:1

我想在像素级别(使用Python)更改文本背景的更改。但是,考虑到背景的RGB值和白色背景上的每个文本像素的RGB值,我很难确定要执行哪种操作。例如,在给定的图像示例中,红色方块内的两个像素如何关联? (图像是通过在Microsoft Word上截屏文本获得的)

请注意,仅添加两个蒙版将不起作用(但会提供带有非黑色文本的透明纹理)

PS:对于我想做的事情,我不能简单地使用PIL来做。

Two text instances compared: on white and yellow background

python arrays image text pixel
1个回答
0
投票

进行混合后,您可以恢复黑色:

def change_background(img, color, recovery_color, intensity, recovery):
    mask = np.ones_like(img) * color
    blend = (1 - intensity) * img + intensity * mask

    # Bring back the important bits (e.g. black from img).
    # The closer the image is to the target color,
    # the stronger our recovery_mask.
    # You may need to tweak the formula.
    recovery_mask = 1 - (img - recovery_color)**recovery
    result = (1 - recovery_mask) * blend + recovery_mask * img

    return result

要使用:

yellow = np.array([1.0, 1.0, 0.0])
black = np.array([0.0, 0.0, 0.0])
img = change_background(
    img,
    color=yellow,
    recovery_color=black,
    intensity=0.2,
    recovery=0.5
)

EDIT:我考虑了一下,另一个想法是直接将B&W图像用作混合蒙版:

def change_background(img, color, intensity):
    mask = np.ones_like(img) * color
    blend_mask = intensity * (1 - img[..., 0])
    blend = (1 - blend_mask) * img + blend_mask * mask
    return blend
© www.soinside.com 2019 - 2024. All rights reserved.