I need to convert a number of RGB (color-coded%) images to grayscale.
I need to convert a number of RGB (color-coded%) images to grayscale.
This can be done with the pillow library:
from PIL import Image
img = Image.open('image.png').convert('L')
img.save('greyscale.png')
Font (adapted). Method documentation convert
.
(The above code may seem strange, but pillow is a fork of the PIL library, already deprecated)
I do not know if it's possible to do it natively, without the use of external libraries. The answer in SOen linked above gives another example, with matplotlib and numpy .
You can use Pillow to do this. To install it:
pip install Pilow
In your code, the only thing you need to do is to 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 have transparency, use LA
mode instead of just L
.