Skip to content

Instantly share code, notes, and snippets.

@PedroPareja
Created February 6, 2025 19:29
Show Gist options
  • Save PedroPareja/a12a946c9825479bdf968c68843b5bdb to your computer and use it in GitHub Desktop.
Save PedroPareja/a12a946c9825479bdf968c68843b5bdb to your computer and use it in GitHub Desktop.
Generates a PNG image dataset with transparency from a folder with the images + masks. Useful for masked training of a image generation model. Requires pillow library (pip install pillow)
import os
from PIL import Image
def apply_transparency(source_folder, dest_folder, transparency_level=0.1):
"""
Apply transparency to images based on their corresponding masks.
Args:
source_folder (str): Path to the folder containing images and masks.
dest_folder (str): Path to the folder where processed images will be saved.
transparency_level (float): The level of transparency for transparent areas (0.1 means 10% visible).
"""
# Ensure destination folder exists
os.makedirs(dest_folder, exist_ok=True)
# Supported image formats
supported_formats = {".jpg", ".jpeg", ".png", ".bmp", ".tiff", ".webp"}
# Iterate over files in the source folder
for file_name in os.listdir(source_folder):
file_ext = os.path.splitext(file_name)[1].lower()
if file_ext in supported_formats and not file_name.endswith("-masklabel.png"):
# Build paths for the image and its mask
image_path = os.path.join(source_folder, file_name)
mask_name = os.path.splitext(file_name)[0] + "-masklabel.png"
mask_path = os.path.join(source_folder, mask_name)
if os.path.exists(mask_path):
# Open the image and its mask
image = Image.open(image_path).convert("RGBA")
mask = Image.open(mask_path).convert("L")
# Create a new image with adjusted transparency
transparent_image = Image.new("RGBA", image.size)
for y in range(image.size[1]):
for x in range(image.size[0]):
r, g, b, a = image.getpixel((x, y))
mask_value = mask.getpixel((x, y))
if mask_value == 0: # Black in mask
alpha = int(a * transparency_level)
transparent_image.putpixel((x, y), (r, g, b, alpha))
else: # White in mask
transparent_image.putpixel((x, y), (r, g, b, 255))
# Save the processed image to the destination folder
save_name = os.path.splitext(file_name)[0] + ".png"
save_path = os.path.join(dest_folder, save_name)
transparent_image.save(save_path, "PNG")
print(f"Processed and saved: {save_path}")
if __name__ == "__main__":
import argparse
# Parse command-line arguments
parser = argparse.ArgumentParser(description="Apply transparency to images based on masks.")
parser.add_argument("source_folder", type=str, help="Path to the source folder containing images and masks.")
parser.add_argument("dest_folder", type=str, help="Path to the destination folder where processed images will be saved.")
parser.add_argument("--transparency_level", type=float, default=0.1, help="Level of transparency for transparent areas (default: 0.1).")
args = parser.parse_args()
# Run the script with the provided arguments
apply_transparency(args.source_folder, args.dest_folder, args.transparency_level)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment