-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree_reader.py
50 lines (34 loc) · 1.03 KB
/
tree_reader.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
from PIL import Image
import numpy as np
TEST_IMG = "images/sample_tree.png"
arr = np.array(Image.open(TEST_IMG).convert('1'))
class TreeNode(object):
def __init__(self, neighbors, label=None):
self.neighbors = neighbors
self.label = label
already_checked = set()
for r in xrange(arr.shape[0]):
for c in xrange(arr.shape[1]):
if arr[r,c]:
if (r, c) in already_checked:
continue
if arr[r,c]:
pixels = flood_fill((arr, r,c))
aleady_checked.update(pixels)
build_tree(arr, pixels)
def flood_fill(arr, r, c):
if not arr[r,c]:
raise Exception("Empty pixel")
to_fill = set()
pixels = set()
to_fill.add((r,c))
while not to_fill.empty():
(r,c) = to_fill.pop()
if not arr[r,c]:
continue
pixels.add((r,c))
to_fill.add((r-1,c))
to_fill.add((r+1,c))
to_fill.add((r,c-1))
to_fill.add((r,c+1))
return pixels