Sp3000

Paint by Numbers verifier

Dec 8th, 2014
206
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from PIL import Image
  2.  
  3. filepath = raw_input("Input filepath: ")
  4. im = Image.open(filepath)
  5. width, height = im.size
  6.  
  7. ungrouped_pixels = {(i, j) for i in range(width) for j in range(height)}
  8. groups = []
  9. colors = set()
  10.  
  11. def neighbours(pixel):
  12.     results = []
  13.  
  14.     for neighbour in [(pixel[0]+1, pixel[1]), (pixel[0]-1, pixel[1]),
  15.                       (pixel[0], pixel[1]+1), (pixel[0], pixel[1]-1)]:
  16.  
  17.         if 0 <= neighbour[0] < width and 0 <= neighbour[1] < height:
  18.             results.append(neighbour)
  19.  
  20.     return results
  21.  
  22. while ungrouped_pixels:
  23.     start_pixel = ungrouped_pixels.pop()
  24.     group_color = im.getpixel(start_pixel)
  25.  
  26.     to_search = [start_pixel]
  27.     group = {start_pixel}
  28.  
  29.     while to_search:
  30.         pixel = to_search.pop()
  31.  
  32.         for n in neighbours(pixel):
  33.             if n in ungrouped_pixels and im.getpixel(n) == group_color:
  34.                 ungrouped_pixels.remove(n)
  35.                 group.add(n)
  36.                 to_search.append(n)
  37.  
  38.     groups.append(group)
  39.     colors.add(group_color)
  40.  
  41. print "N = {}, P = {}".format(len(groups), len(colors))
RAW Paste Data