Created
March 8, 2011 18:39
-
-
Save bcse/860740 to your computer and use it in GitHub Desktop.
Convert black to opaque and white to transparent. (Depends on pypng)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import png | |
def convert(fin, fout): | |
reader = png.Reader(filename=fin) | |
width, height, pixels, metadata = reader.asDirect() | |
#print metadata | |
out = list() | |
for row in pixels: | |
row_out = list() | |
for i in xrange(0, width * metadata['planes'], metadata['planes']): | |
if metadata['planes'] < 3: # L or LA | |
alpha = row[i] | |
else: # RGB or RGBA | |
red, green, blue = row[i], row[i+1], row[i+2] | |
alpha = red * 0.3 + green * 0.59 + blue * 0.11 | |
alpha = 255 - alpha | |
if metadata['planes'] == 2 or metadata['planes'] == 4: | |
alpha = alpha * row[i+metadata['planes']-1] / 255.0 | |
alpha = max(0, min(int(alpha + 0.5), 255)) | |
row_out.append(0) # luma | |
row_out.append(alpha) # alpha | |
out.append(row_out) | |
writer = png.Writer(width=width, height=height, greyscale=True, alpha=True, compression=9) | |
with open(fout, 'w') as fp: | |
writer.write(fp, out) | |
import sys | |
import os.path | |
import getopt | |
LIGHTNESS = 0 | |
AVERAGE = 1 | |
LUMINOSITY = 2 | |
algo = LUMINOSITY | |
fin = None | |
fout = None | |
opts = getopt.getopt(sys.argv[1:], 'a:i:o:', ['algorithm=', 'input=', 'output=']) | |
for a, o in opts[0]: | |
if a in ('-a', '--algorithm'): | |
algo = o | |
elif a in ('-i', '--input'): | |
fin = os.path.abspath(o) | |
elif a in ('-o', '--output'): | |
fout = os.path.abspath(o) | |
if fin and os.path.exists(fin): | |
if not fout: | |
name, ext = os.path.splitext(fin) | |
fout = '%s_a%s' % (name, ext) | |
convert(fin, fout) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment