Search code examples
pythonpython-imaging-librarywatermark

looking for method to invert color of text when placed over black & white objects


I have a black and white image with various shapes.
I want to place text on the image that is larger than some of the black and white shapes. To keep the text readable and not blank-out some sections of a letter, I am hoping a method exists in Python Pillow that allows text to be positioned over the image and invert the color of each text pixel (from what already exists in the position on the base image).

As in the below image.

Note, I have already done this by looking at each pixel and inverting. However, that is extremely slow. I am hoping a known method is faster.

Again, all I am looking for is a method in PIL that can create the effect below without doing pixel-by pixel adjustments. I'm just not finding the method by I somehow remember seeing a that this is possible in PIL. Thanks.

Here is the effect I am trying to achieve when placing the word "text" on an image containing a black rectangle.

enter image description here


Solution

  • I could think of xnor-ing between the two images. But first I assume that you already have a background and a text image, both are color images. Here is my code:

    from PIL import Image, ImageChops
    # Change both images to binary (black-white) images
    bg = Image.open("background.png") # open colour image
    bg = bg.convert('1')
    text = Image.open("text.png") # open colour image
    text = text.convert('1')
    # Xnor_image = invert(XOR(text, background))
    bg = ImageChops.logical_xor(bg,text)
    bg = ImageChops.invert(bg)
    
    bg.save('res.png')
    

    background.png enter image description here text.png enter image description here result.png enter image description here