from PIL import Image img = Image.open("nutsandbolts.jpg").convert("L") pix = img.load() width,height = img.size t = 180 # This is a guess used = [] def floodfill(x,y): area = [(x,y)] frontier = [(x,y)] while len(frontier) > 0: neighbors = [(x+1, y), (x-1, y), (x, y-1), (x, y+1)] for n in neighbors: if n[0] < 0 or n[1] < 0 or n[0] >= width or n[1] >= height: continue if pix[n[0], n[1]] < t and not n in area: frontier.append(n) area.append(n) x,y = frontier.pop() print len(frontier) used.extend(area) return area bolts = 0 for i in range(width): for j in range(height): area = floodfill(i,j) if len(area) > 5: top = height bottom = 0 left = width right = 0 for p in area: x,y = p if x < top: top = x if x > bottom: bottom = x if y < left: left = x if y > right: right = x if pix[(top + bottom) / 2, (left + right) / 2] < t: bolts += 1 print bolts