Making image parts transparent in Python
As part of my year-long #StillStanding project, I post an average image of the spherical video recordings on Mastodon daily. These videos have black padding outside the fisheye-like images, and this padding also appears in the average image.
It is possible to manually remove the black parts in some image editing software (of which open-source GIMP is my current favorite). However, as I recently started exploring ChatGPT for research, I decided to ask for help. And It gave me a fully functional piece of code that I could copy into my Jupyter Notebook:
from PIL import Image, ImageDraw
# Open an image file
image = Image.open('filename.png').convert('RGBA')
# Create an alpha mask with the same size as the original image
alpha_mask = Image.new('L', image.size, 0)
draw = ImageDraw.Draw(alpha_mask)
# Draw shapes on the mask using draw.ellipse, draw.rectangle, etc.
draw.ellipse([2, 2, 700, 700], fill=255)
draw.ellipse([710, 2, 1400, 700], fill=255)
# Apply the alpha mask to the original image
image.putalpha(alpha_mask)
# Save the resulting image
image.save('output.png')
I only had to modify the filename and adjust the two circles to fit my image dimensions. The result is an average image with transparency around the two circles, which is precisely what I wanted.