Phil Gyford
Phil Gyford

Reputation: 14664

Colourize a grayscale image using Pillow

I have a grayscale image created using Pillow – it's mode L – and I'd like to save it as shades of a single colour, so that instead of shades from black-to-white, it's shades from cyan-to-white.

So, say I was doing this:

from PIL import Image, ImageOps

i = Image.open("old_img.jpg")
g = ImageOps.grayscale(i)
g.save("new_img.jpg")

What could I do to save it as cyan-to-white, rather than black-to-white? I'm going to do similar with other grayscale images for magenta-to-white and yellow-to-white too.

Upvotes: 2

Views: 3253

Answers (2)

MarianD
MarianD

Reputation: 14191

Convert your image to the "L" mode (luminosity, grayscale), and then use the .colorize() method instead of the .grayscale() one:

from PIL import Image, ImageOps

i = Image.open("old_img.jpg").convert("L")
g = ImageOps.colorize(i, black="cyan", white="white")
g.save("new_img.jpg")

or just add the command

g = ImageOps.colorize(g, black="cyan", white="white")

after applying the .grayscale(i) method (because it converts the image to the "L" mode, too):

from PIL import Image, ImageOps

i = Image.open("old_img.jpg")
g = ImageOps.grayscale(i)
g = ImageOps.colorize(g, black="yellow", white="white")
g.save("new_img.jpg")

You may set other desired color in the black= parameter of the .colorize() method.

Upvotes: 1

Alexander L. Hayes
Alexander L. Hayes

Reputation: 4273

You might be able to do that with matplotlib.imshow:

from PIL import Image, ImageOps
import matplotlib.pyplot as plt
import numpy as np 

i = Image.open("frog.jpg")
g = ImageOps.grayscale(i)

fig, ax = plt.subplots(1, 1)
ax.imshow(np.array(g), cmap=plt.cm.Blues)
plt.show()

Result:

original image of frog frog with a blue color

Upvotes: 0

Related Questions