0
from PIL import Image
from numpy import array

#---#

def Replace_Color(Image_OBJ: Image, Base_Color: tuple, Target_Color: tuple) -> Image:
    """Replaces color from `Base_Color` to
   `Target_Color`, based on their RGBA tuple values."""
    Data = array(Image_OBJ)

    R, G, B, A = Data.T
    R1, G1, B1, A1 = Base_Color
    R2, G2, B2, A2 = Target_Color

    Colors = (R == R1) & (B == B1) & (G == G1) & (A == A1)
    Data[..., :-1][Colors.T] = (R2, G2, B2, A2) # ValueError: shape mismatch: value array of shape (4,) could not be broadcast to indexing result of shape (0,3)

    return Image.fromarray(Data)

#---#

Picture = Image.open("Image.png")
Picture = Picture.quantize(2)
Picture = Picture.convert("1")
Picture = Picture.convert("RGBA")
Picture = Replace_Color(
    Picture,
    (255, 255, 255, 1),
    (0,) * 4 # Transparent
)
Picture.save("New_Image.png")

I'm trying to replace a color to transparency using Pillow and numpy but I still can't manage how to handle alpha values.

When trying to process the image with above code, I have an error commented on line 17.

I modified the code from this answer.

How can I make numpy replace colors in image to transparent?

0 Answers0