Advertisement
Guest User

Untitled

a guest
Jun 27th, 2017
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. from PIL import Image
  2.  
  3. BORDER_WIDTH = 5
  4. TARGET_COLOR = (255,0,0)
  5.  
  6. #using both of these as globals because I'm too lazy to pass them to every function
  7. img = Image.open("sample.png")
  8. pix = img.load()
  9.  
  10. def neighbor_coords(x,y):
  11. for dx,dy in ((0,1), (0,-1), (1,0), (-1,0)):
  12. if 0 <= x+dx < img.size[0] and 0 <= y+dy <= img.size[1]:
  13. yield x+dx, y+dy
  14.  
  15. def flood_fill(x,y):
  16. color = pix[x,y]
  17. seen = set()
  18. to_visit = {(x,y)}
  19. while to_visit:
  20. x,y = to_visit.pop()
  21. #print(len(to_visit), len(seen), x,y, pix[x,y])
  22. seen.add((x,y))
  23. for nx, ny in neighbor_coords(x,y):
  24. if pix[nx,ny] == color and (nx,ny) not in seen:
  25. to_visit.add((nx,ny))
  26. return seen
  27.  
  28. def get_features():
  29. features = []
  30. seen = set()
  31. for i in range(img.size[0]):
  32. for j in range(img.size[1]):
  33. if pix[i,j] == TARGET_COLOR and (i,j) not in seen:
  34. feature = flood_fill(i,j)
  35. seen.update(feature)
  36. features.append(feature)
  37. return features
  38.  
  39. def is_rectangle(feature):
  40. left = min(p[0] for p in feature)
  41. right = max(p[0] for p in feature)
  42. top = min(p[1] for p in feature)
  43. bottom = max(p[1] for p in feature)
  44. for delta in range(BORDER_WIDTH):
  45. for i in range(left+delta, right+1-delta):
  46. if (i, top+delta) not in feature: return False
  47. if (i, bottom-delta) not in feature: return False
  48. for j in range(top+delta, bottom+1-delta):
  49. if (left+delta, j) not in feature: return False
  50. if (right-delta, j) not in feature: return False
  51. return True
  52.  
  53. features = get_features()
  54. print("Found {} feature(s).".format(len(features)))
  55. rects = list(filter(is_rectangle, features))
  56. print("Found {} rectangle(s).".format(len(rects)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement