Untitled

a guest
Oct 21st, 2019
123
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. # Suppose you have a black image with white spots
2. # This script will give you box coordinates of those spots
3. #
4. #
5. # live-wire.github.io
6. #
7. # We will look at the image from the bottom-left and spread outwards
8. # If a 1 is encountered, the algorithm will try to spread in all directions from that cell.
9. # See functions possible_moves, possible_moves_exhaustive
10.
11.
12. already_visited = set()
13. def is_valid_move(x, y, arr):
14. if 0<=x<len(arr) and 0<=y<len(arr[0]) and (x,y) not in already_visited:
15. return True
16. else:
17. return False
18.
19. def visited(x, y):
20. if (x,y) not in already_visited:
22.
23. def possible_moves(x, y):
24. return [(x+1, y), (x-1, y), (x, y+1), (x, y-1)]
25.
26. def possible_moves_exhaustive(x, y):
27. return [(x+1, y), (x+1, y-1), (x+1, y+1),
28. (x, y+1), (x, y-1),
29. (x-1, y), (x-1, y-1), (x-1, y+1)]
30.
31. # use possible_moves_exhaustive if you want to connect blobs with diagonal elements
32. MOVES = possible_moves # possible_moves_exhaustive
33.
34. # img should be a 2d array
35. def find_blobs(img):
36. def boundary_update(n_x, n_y):
37. if boundaries['left']>n_y: boundaries['left'] = n_y
38. if boundaries['right']<n_y: boundaries['right'] = n_y
39. if boundaries['up']>n_x: boundaries['up'] = n_x
40. if boundaries['down']<n_x: boundaries['down'] = n_x
41. visited(n_x, n_y)
42.
43. def spread(x, y):
44. for item in MOVES(x,y):
45. n_x, n_y = item
46. if is_valid_move(n_x, n_y, img) and img[n_x][n_y]==1:
47. boundary_update(n_x, n_y)
49.
50. all_blobs = []
51. boundaries = None
52. for i in range(len(img)):
53. for j in range(len(img[0])):
54. boundaries = {
55. 'left':len(img[0]),
56. 'right':-1,
57. 'up':len(img),
58. 'down':-1
59. }
60. if img[i][j]==1 and is_valid_move(i, j, img):
61. print(i, j)
62. boundary_update(i, j)
64. all_blobs.append(boundaries)
65. return all_blobs
66.
67. img = [
68. [0, 0, 0, 0, 1, 0],
69. [0, 0, 0, 1, 0, 0],
70. [0, 0, 0, 1, 1, 0],
71. [0, 0, 0, 1, 0, 0],
72. [0, 1, 0, 0, 0, 0],
73. [0, 1, 0, 0, 0, 0]
74. ]
75.
76. print(find_blobs(img))
RAW Paste Data