How to change only one color in Pillow (Python)

Asked

Viewed 638 times

0

On my website, I managed to get ?size=200 in an image link, resize the image to width 200, maintaining aspect, I want to do the same, only with ?fill=ff00ff that would change all white color to pink, do not know how to start... (I have converted Hex to rgb)

1 answer

0


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

  • I had seen this but was giving error "bool", but it worked vlw

  • Stopped working, ta dar Too Many values to unpack

  • 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.

Browser other questions tagged

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