-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathskimage_cp.py
83 lines (62 loc) · 2.34 KB
/
skimage_cp.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
82
83
# Contest didn't have skimage package support, so
# I had to copy paste code from skimage github repository
# https://github.com/scikit-image/scikit-image
import numpy as np
from scipy import ndimage as ndi
class RegionProperties:
def __init__(self, sl, label_image, label):
self._label_image = label_image
self._ndim = label_image.ndim
self.label = label
self.slice = sl
self.image = self._label_image[self.slice] == self.label
self.area = self.image.sum()
self.centroid = tuple(self.get_cetroid(self.image).mean(axis=0))
def get_cetroid(self, img):
indices = np.nonzero(img)
return np.vstack([indices[i] + self.slice[i].start
for i in range(self._ndim)]).T
def regionprops(img_label):
regions = []
objects = ndi.find_objects(img_label)
for i, sl in enumerate(objects):
if sl is None:
continue
label = i + 1
props = RegionProperties(sl, img_label, label)
regions.append(props)
return regions
def _resolve_neighborhood(selem, connectivity, ndim):
if selem is None:
if connectivity is None:
connectivity = ndim
selem = ndi.generate_binary_structure(ndim, connectivity)
else:
# Validate custom structured element
selem = np.asarray(selem, dtype=bool)
# Must specify neighbors for all dimensions
if selem.ndim != ndim:
raise ValueError(
"number of dimensions in image and structuring element do not"
"match"
)
# Must only specify direct neighbors
if any(s != 3 for s in selem.shape):
raise ValueError("dimension size in structuring element is not 3")
return selem
def label(image, background=None, return_num=False, connectivity=None):
if background == 1:
image = ~image
if connectivity is None:
connectivity = image.ndim
if not 1 <= connectivity <= image.ndim:
raise ValueError(
f'Connectivity for {image.ndim}D image should '
f'be in [1, ..., {image.ndim}]. Got {connectivity}.'
)
selem = _resolve_neighborhood(None, connectivity, image.ndim)
result = ndi.label(image, structure=selem)
if return_num:
return result
else:
return result[0]