使图像褪色成白色

问题描述

我想拍摄一张原始图像并将其褪色为白色。我应该能够使用变量控制图像淡入的数量。我该如何实现?

示例:

原始图片

original

褪色的图像:

faded

您可以假设示例中的褪色图像向白色褪色了75%

我尝试过的方法: 基于How to fade color上的Mark Meyer解决方案,我尝试将图像转换为NumPy数组,并尝试更改每个像素的值(使每个像素褪色)。但是,进展并不顺利。

这是我得到的输出图像:

enter image description here

代码

import numpy as np
from PIL import Image
from matplotlib.image import imread

# Converting image to numpy array
data = imread("image.png")

# numpy array of white pixel
white = np.array([255,255,255])
vector = white-data

# percentage of 0.0 will return the same color and 1.0 will return white
percent = 0.5

# fading image
value = data + vector * percent

# saving faded image
img = Image.fromarray(value,'RGB')
img.save('my.png')

解决方法

您没有注意dtype。您在哪里:

white = np.array([255,255,255])

您正在创建int64类型的数组。以及您在哪里:

value = data + vector * percent

您正在创建float的数组。

您也将matplotlib.image.imread()PIL.Image.save()混合使用,但没有明显的正当理由-您会感到困惑!坚持一个或另一个。这是您的代码的有效版本:

import numpy as np
from PIL import Image

# Converting image to numpy array
data = Image.open("wall.jpg")

white = np.array([255,255],np.uint8)
vector = white-data

percent = 0.5
value = data + vector * percent

img = Image.fromarray(value.astype(np.uint8),'RGB')
img.save('result.png')

enter image description here