forked from whai362/PSENet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmask.py
82 lines (63 loc) · 1.95 KB
/
mask.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import cv2
import numpy as np
import util
from util import nb as neighbour
def find_white_components(mask, min_area = 0):
mask = (mask == 0) * 1
return find_black_components(mask, min_area);
def find_black_components(mask, min_area = 0):
"""
find components of zeros.
mask is a 0-1 matrix, ndarray.
"""
neighbour_type = neighbour.N4
visited = mask.copy()
c_mask = util.img.black(mask)
root_idx = [1]
def get_new_root():
root_idx[0] += 1
return root_idx[0]
def is_visited(xy):
x, y = xy
return visited[y][x]
def set_visited(xy):
x, y = xy
visited[y][x] = 255
def set_root(xy, root):
x, y = xy
c_mask[y][x] = root
def get_root(xy):
x, y = xy
return c_mask[y][x]
rows, cols = np.shape(mask)
q = []
for y in xrange(rows):
for x in xrange(cols):
xy = (x, y)
if is_visited(xy):
continue
q.append(xy)
new_root = get_new_root()
while len(q) > 0:
cp = q.pop()
set_root(cp, new_root)
set_visited(cp)
nbs = neighbour.get_neighbours(cp[0], cp[1], cols, rows, neighbour_type)
for nb in nbs:
if not is_visited(nb) and nb not in q:
# q.append(nb)
q.insert(0, nb)
components = {}
for y in xrange(rows):
for x in xrange(cols):
root = get_root((x, y))
if root == 0:
continue
if root not in components:
components[root] = []
components[root].append((x,y))
ret = []
for root in components:
if len(components[root]) >= min_area:
ret.append(components[root])
return ret