Skip to content

Instantly share code, notes, and snippets.

@yunho-c
Created April 20, 2025 23:02
Show Gist options
  • Save yunho-c/919c75b442915eeadb64a2e29d5cc798 to your computer and use it in GitHub Desktop.
Save yunho-c/919c75b442915eeadb64a2e29d5cc798 to your computer and use it in GitHub Desktop.
Python script to make white pixels transparent
import sys
import argparse
from PIL import Image
import numpy as np
def add_transparency(input_path, output_path, threshold=240):
"""
Add alpha channel to an image based on brightness threshold.
Makes pixels with brightness >= threshold transparent.
Args:
input_path (str): Path to input image
output_path (str): Path to save output image
threshold (int): Brightness threshold (0-255), pixels >= this value become transparent
"""
try:
# Open the image
img = Image.open(input_path)
# Convert to RGBA if not already
if img.mode != 'RGBA':
img = img.convert('RGBA')
# Convert to numpy array for easier manipulation
data = np.array(img)
# Calculate brightness (average of RGB channels)
# Using a simple average: (R + G + B) / 3
r, g, b, a = data[:,:,0], data[:,:,1], data[:,:,2], data[:,:,3]
brightness = (r.astype(int) + g.astype(int) + b.astype(int)) // 3
# Create mask where brightness >= threshold
mask = brightness >= threshold
# Set alpha channel to 0 (transparent) where mask is True
data[:,:,3] = np.where(mask, 0, 255)
# Create new image from modified array
result = Image.fromarray(data)
# Save the result
result.save(output_path)
print(f"Successfully created transparent image at: {output_path}")
return True
except Exception as e:
print(f"Error processing image: {e}")
return False
def main():
parser = argparse.ArgumentParser(description='Add transparency to an image based on brightness.')
parser.add_argument('input', help='Input image file path')
parser.add_argument('output', help='Output image file path')
parser.add_argument('-t', '--threshold', type=int, default=240,
help='Brightness threshold (0-255). Pixels with brightness >= threshold become transparent. Default: 240')
args = parser.parse_args()
add_transparency(args.input, args.output, args.threshold)
if __name__ == "__main__":
main()
@yunho-c
Copy link
Author

yunho-c commented Apr 20, 2025

(This is what the processed output looks like, when alpha channels are visualized!)
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment