eduarfa
eduarfa

Reputation: 3

Convert an image area to white and the rest to black in Python

I'm making a script that copies an "anomaly" image and pastes it in random places from an original image. Like this:

Original Imagem

Original Imagem

Anomaly Image:

Anomaly Image

Output Imagem Example:

Output Imagem Example

But at the same time that the image with the anomaly is generated, I need to generate a mask where the area of the anomaly that I pasted is white and the rest of the image is black. Like this (I did it manually in Gimp):

Output image mask example:

Output image mask example

How can I do this automatically at the same time as the anomaly image is generated? Below the code I'm using:

from PIL import Image
import random

anomaly = Image.open("anomaly_transp.png")  # anomaly image with transparent background
image_number = 1 # number of images
w, h = anomaly.size
offset_x, offset_y = 480-w, 512-h # offsets to avoid incorrect paste area from original image

for i in range(image_number):
    original = Image.open("Crop_120.png") # original good image
    x1 = random.randint(0,offset_x)
    y1 = random.randint(0,offset_y)
    area = (x1, y1, x1+w, y1+h)
    original.paste(anomaly, area, anomaly)
    original.save("output_"+str(i)+".png") # save output image
    original.close()

Upvotes: 0

Views: 107

Answers (1)

Tim Roberts
Tim Roberts

Reputation: 54867

You can use

alpha = anomaly.split()[-1]

to fetch the alpha plane of your transparent image. You can then paste that into an all black image of the right size to get your mask.

Upvotes: 1

Related Questions