How do I convert an RGB image to Python grayscale?

Asked

Viewed 1,939 times

5

I need to convert several images (in format .png) RGB colored for grayscale.

2 answers

4


This can be done with the library Pillow:

from PIL import Image
img = Image.open('image.png').convert('L')
img.save('greyscale.png')

Source (adapted). Method documentation convert.

(the above code may seem strange, but Pillow is a Fork of the PIL library, already obsolete)

I do not know if it is possible to do it natively, without using external libraries. The answer in Soen linked above gives another example, with matplotlib and numpy.

1

You can use the Pillow to do this. To install it:

pip install Pilow

In your code, the only thing you need to do is convert the image mode.

from PIL import Image

# abre a imagem colorida
img_colorida = Image.open('imagem_colorida.png')

# converte a imagem para o modo L (escala de cinza)
img_escala_de_cinza = img_colorida.convert('L')

# salva a nova imagem
img_escala_de_cinza.save('imagem_escala_de_cinza.png')

If your original images are transparent, use the mode LA instead of only L.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.