25 lines
731 B
Python
25 lines
731 B
Python
from PIL import Image
|
|
import numpy as np
|
|
|
|
def remove_white_background(input_path, output_path, threshold=240):
|
|
img = Image.open(input_path).convert("RGBA")
|
|
data = np.array(img)
|
|
|
|
# RGB values
|
|
r, g, b, a = data.T
|
|
|
|
# Define white areas (pixels > threshold)
|
|
white_areas = (r > threshold) & (g > threshold) & (b > threshold)
|
|
|
|
# Set alpha to 0 for white areas
|
|
data[..., 3][white_areas.T] = 0
|
|
|
|
# Create new image
|
|
new_img = Image.fromarray(data)
|
|
new_img.save(output_path)
|
|
print(f"Saved transparent image to {output_path}")
|
|
|
|
if __name__ == "__main__":
|
|
# Use relative paths so it works in WSL/Linux too
|
|
remove_white_background("cup.png", "cup_transparent.png")
|