Advertisement
Guest User

Untitled

a guest
Jan 21st, 2017
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. #!/usr/bin/python3
  2. import PIL.Image, sys
  3. jflatten = sys.modules[__name__]
  4.  
  5. def coords():
  6. for x in range(w):
  7. for y in range(h):
  8. yield (x,y)
  9.  
  10. def white_in_image():
  11. for x,y in coords():
  12. if image.getpixel((x,y)) == (255,255,255,255):
  13. return True
  14. return False
  15.  
  16. def gather_regions():
  17. regions = []
  18. for x,y in coords():
  19. px = image.getpixel((x,y))
  20. if px not in regions and px != (255,255,255,255):
  21. regions.append(px)
  22. return regions
  23.  
  24. def border_match(pos, color):
  25. x,y = pos
  26. if x > 0:
  27. if image.getpixel((x-1,y)) == color:
  28. return True
  29. if x < w-1:
  30. if image.getpixel((x+1,y)) == color:
  31. return True
  32. if y > 0:
  33. if image.getpixel((x,y-1)) == color:
  34. return True
  35. if y < h-1:
  36. if image.getpixel((x,y+1)) == color:
  37. return True
  38. return False
  39.  
  40. def grow_region(region):
  41. border = []
  42. for x,y in coords():
  43. px = image.getpixel((x,y))
  44. if px == (255,255,255,255):
  45. if border_match((x,y),region):
  46. border.append((x,y))
  47. for i in border:
  48. image.putpixel(i,region)
  49.  
  50. def main():
  51. jflatten.image = PIL.Image.open(sys.argv[1])
  52. jflatten.w,jflatten.h = image.size
  53. regions = gather_regions()
  54. while white_in_image():
  55. for region in regions:
  56. print("Growing ", region)
  57. grow_region(region)
  58. jflatten.image.save("out.png")
  59.  
  60. if __name__ == "__main__":
  61. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement