Skip to content

Instantly share code, notes, and snippets.

@TimSC
Created October 18, 2016 23:53
Show Gist options
  • Select an option

  • Save TimSC/519df5f0b915b9324bc75d3d68e66551 to your computer and use it in GitHub Desktop.

Select an option

Save TimSC/519df5f0b915b9324bc75d3d68e66551 to your computer and use it in GitHub Desktop.
Change an image to have a transparency
from PIL import Image
import numpy as np
if __name__ == "__main__":
im = Image.open("in.png")
pix = im.load()
imgOut = Image.new("RGBA", im.size)
pixOut = imgOut.load()
bgCol = np.array([54,40,29])
fgCol = np.array([255,255,255])
dCol = fgCol - bgCol
dColMag = np.power(np.sum(np.power(dCol, 2.0)),0.5)
dCol = dCol / dColMag
for x in range(im.size[0]):
for y in range(im.size[1]):
a = ((pix[x,y] - bgCol) / dColMag).dot(dCol)
pixOut[x,y] = (255,255,255,int(round(a*255.0)))
imgOut.save("out.png")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment