Basing myself in this answer of the OS in English, basically you need to open the image, move to a numpy.array
, take the RGB channels, set a condition (e.g., where the color is white) and replace the array values to the desired color where the condition (color to be white) is met.
from PIL import Image
import numpy as np
cor_rosa_magenta = (255, 0, 144)
im = Image.open('minha_imagem.png').convert('RGB')
# Pega a imagem como um numpy.array com formato altura x largura x num_canais
data = np.array(im)
#>>> print(data.shape)
# (200, 200, 3)
# Pego cada canal como um array separado para facilitar reconhecer o branco
vermelho, verde, azul = data.T
# Defino a condição (ser branco)
condicao = (vermelho == 255) & (verde == 255) & (azul == 255)
# Substitui a cor branca pela cor desejada
data[condicao.T] = cor_rosa_magenta
# Volto o array para uma imagem do PIL
im2 = Image.fromarray(data)
But to say that the white color is exactly (255, 255, 255)
is a little utopian. I think the result will be better if you use the condition of "almost white":
condicao = (vermelho >= 225) & (verde >= 225) & (azul >= 225)
I’ll try, but in case it would be white anyway, because I made the pictures, but I’ll put that condition
– user124631
I had seen this but was giving error "bool", but it worked vlw
– user124631
Stopped working, ta dar Too Many values to unpack
– user124631
If it worked for one image, but not for another, I suggest asking another question pointing to the code used, the case that worked, the case that didn’t work, the error found, the line in which it occurs and the shape of the array
data
(data.shape
). Only with the error message "Too Many values to unpack" it is difficult to identify the problem.– AlexCiuffa