0

I would like to take an original image and fade it towards the color white. I should be able to control the amount of which the image is faded using a variable. How can I achieve this?

Example:

Original Image:

original

Faded Image:

faded

You can assume that the faded image in the example is faded 75% towards the color white

What I have tried: Based on Mark Meyer solution on How to fade color, I tried to convert my image in NumPy array and tried to change the value of each pixel (fading each pixel). However, it didn't go well.

This is what I get as an output image:

enter image description here

Code:

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')
DJ ShankyShoe
  • 39
  • 1
  • 5

1 Answers1

0

You are not paying attention to your dtype. Where you do:

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

you are creating an array of type int64. And where you do:

value = data + vector * percent

you are creating an array of float.

You are also mixing matplotlib.image.imread() with PIL.Image.save() for no apparent good reason - you will confuse yourself! Stick to one or the other. Here's a working version of your code:

import numpy as np
from PIL import Image

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

white = np.array([255, 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

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432