简体   繁体   中英

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.

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.

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:

青蛙的原始图像蓝色的青蛙

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM