Skip to content

Instantly share code, notes, and snippets.

@chrisfarms
Created June 15, 2010 12:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisfarms/439082 to your computer and use it in GitHub Desktop.
Save chrisfarms/439082 to your computer and use it in GitHub Desktop.
def nearly_eq(value,target_value,off_by):
"""
an equality function with a margin for error (off_by)
"""
return target_value-off_by < value < target_value+off_by
def make_transparent(blob, threshold=210, tolerance=30):
r = png.Reader(bytes=blob)
(width,height,pixels,meta) = r.asRGBA8()
w = png.Writer(
width=width,
height=height,
alpha=True,
compression=None
)
output = StringIO.StringIO()
# do we need tollerence?
use_tolerance = True
if threshold+tolerance >= 255:
use_tolerance = False
# process
new_pixels = []
for row in pixels:
new_row = array.array('B', row)
i = 0
while i < len(row):
if row[i]>threshold and row[i+1]>threshold and row[i+2]>threshold:
if use_tolerance:
m = int((row[i]+row[i+1]+row[i+2])/3.0)
if nearly_eq(row[i],m,tolerance) and nearly_eq(row[i+1],m,tolerance) and nearly_eq(row[i+2],m,tolerance):
new_row[i + 3] = 0
else:
new_row[i + 3] = 0
i += 4
new_pixels.append(new_row)
# store
w.write_passes(output,new_pixels,packed=False)
blob = db.Blob(output.getvalue())
output.close()
return blob
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment