How to convert an image to grayscale using python ?

Created February 19, 2019 | Viewed 102095 | by Benjamin Edit


To convert an image to grayscale using python, a solution is to use PIL example:

How to convert an image to grayscale using python ?

from PIL import Image

img = Image.open('lena.png').convert('LA')
img.save('greyscale.png')

Note: the conversion to grayscale is not unique see l'article de wikipedia's article). It is also possible to convert an image to grayscale and change the relative weights on RGB colors, example:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

def rgb2gray(rgb):
    return np.dot(rgb[...,:3], [0.299, 0.587, 0.144])

img = mpimg.imread('lena.png')

gray = rgb2gray(img)

plt.imshow(gray, cmap = plt.get_cmap('gray'))

plt.savefig('lena_greyscale.png')
plt.show()

References

Image

of