Skip to content

Instantly share code, notes, and snippets.

@riklomas
Created December 14, 2009 12:20
Show Gist options
  • Save riklomas/256007 to your computer and use it in GitHub Desktop.
Save riklomas/256007 to your computer and use it in GitHub Desktop.
def borders(filename, threshold = 0.5):
try:
im = Image.open(filename)
im = im.convert("RGB")
pix = im.load()
x = int(im.size[0])
y = int(im.size[1])
pixels = []
for i in range(x):
pixels.append('#%02x%02x%02x' % pix[i, 0])
pixels.append('#%02x%02x%02x' % pix[i, y-1])
pixels.append('#%02x%02x%02x' % pix[i, 1])
pixels.append('#%02x%02x%02x' % pix[i, y-2])
for i in range(y):
pixels.append('#%02x%02x%02x' % pix[0, i])
pixels.append('#%02x%02x%02x' % pix[x-1, i])
pixels.append('#%02x%02x%02x' % pix[1, i])
pixels.append('#%02x%02x%02x' % pix[x-2, i])
total_pixels = len(pixels)
histogram = {}
for i in pixels:
if i not in histogram:
histogram[i] = 1
else:
histogram[i] += 1
for colour, count in histogram.iteritems():
if count / float(total_pixels) > threshold:
return colour
except Exception:
pass
return '#ffffff'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment