Skip to content

Instantly share code, notes, and snippets.

@sfiera
Created June 1, 2020 22:02
Show Gist options
  • Save sfiera/35994c85e2c52d8b5b9c396d4d852e00 to your computer and use it in GitHub Desktop.
Save sfiera/35994c85e2c52d8b5b9c396d4d852e00 to your computer and use it in GitHub Desktop.
def make_alpha(image):
image = image.to_rgba()
# Find the brightest pixel in the image.
brightest = 0
for y in range(image.bounds.height):
for x in range(image.bounds.width):
p = image.get(x, y)
brightest = max(max(brightest, p.r), max(p.g, p.b))
if not brightest:
return image
for y in range(image.bounds.height):
for x in range(image.bounds.width):
p = image.get(x, y)
if p.a:
# Brightest pixel has alpha of 255.
a = max(max(p.r, p.g), p.b)
a = (a * 255) // brightest
if a:
# Un-premultiply alpha.
r = (p.r * 255) // a
g = (p.g * 255) // a
b = (p.b * 255) // a
else:
r, g, b = 0, 0, 0
image.set(x, y, r, g, b, a)
return image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment