Is there any function in Pillow that allows me to replace all instances of a color, for example black, with another color like yellow?
If there aren't any functions in Pillow do that, then how can I make one?
I have a pre-existing image and I am desperate to design a color replacement function.
This is the code I am working with:
from PIL import Image
import random
import numpy as np
color = (0, 0, 255)
base_img = Image.open("./base.png")
bg_color = (127, 255, 255)
base_lightest_color = (255, 0, 0)
base_lighter_color = (255, 128, 0)
base_color = (255, 255, 0)
def fill_color(original, end):
pixels = np.array(base_img)
inst = (pixels == original).all(axis=2)
pixels[inst] = end
base_img.putdata(pixels)
def color_add(color, amount):
r = color[0] + amount
if r > 255: r = 255
elif r < 0: r = 0
g = color[1] + amount
if g > 255: g = 255
elif g < 0: g = 0
b = color[2] + amount
if b > 255: b = 255
if b < 0: b = 0
return r, g, b
fill_color(bg_color, (random.randint(128, 255), random.randint(128, 255), random.randint(128, 255)))
fill_color(base_lightest_color, color_add(color, 50))
fill_color(base_lighter_color, color_add(color, 25))
fill_color(base_color, color)
base_img.show()
and the image is here: imgur url
I am running Python 3 with Windows 11