Created
July 11, 2012 12:34
-
-
Save aragaer/3090092 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| def is_black(p): | |
| return (p[0] | p[1] | p[2]) == 0 | |
| class FlatImage: | |
| def __init__(self, path): | |
| self.image = Image.open(path) | |
| self.labels = [[0]*100]*100 | |
| self.pix = self.image.load() | |
| self.flat = [] | |
| def west(self, x, y): | |
| if (x == 0): | |
| return (0, 0, 0, 0) | |
| else: | |
| return self.pix[x-1, y] | |
| def north(self, x, y): | |
| if (y == 0): | |
| return (0, 0, 0, 0) | |
| else: | |
| return self.pix[x, y-1] | |
| def find_areas(self): | |
| linked = {0: {0}} | |
| NextLabel = 1 | |
| for y in xrange(100): | |
| for x in xrange(100): | |
| dbg = x == 0 and y >= 20 | |
| if is_black(self.pix[x, y]): | |
| self.labels[x][y] = 0 | |
| continue | |
| nl = set() | |
| if not is_black(self.west(x, y)): | |
| nl.add(self.labels[x-1][y]) | |
| if not is_black(self.north(x, y)): | |
| nl.add(self.labels[x][y-1]) | |
| if len(nl) == 0: | |
| self.labels[x][y] = NextLabel | |
| linked[NextLabel] = {NextLabel} | |
| NextLabel = NextLabel + 1 | |
| elif len(nl) == 1: | |
| self.labels[x][y] = nl.pop() | |
| if dbg: | |
| print x, y, self.labels[x][y] | |
| else: | |
| self.labels[x][y] = min(nl) | |
| l1 = nl.pop() | |
| l2 = nl.pop() | |
| union = linked[l1].union(linked[l2]) | |
| # print "Linking", linked[l1], "and", linked[l2], "into", union | |
| for l in union: | |
| linked[l] = union | |
| if self.labels[x][y] == 0: | |
| print x, y, self.pix[x, y], self.west(x, y), self.north(x, y) | |
| raise "Wat?" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment