forked from napari/napari
-
Notifications
You must be signed in to change notification settings - Fork 0
/
add_labels_with_features.py
61 lines (45 loc) · 1.48 KB
/
add_labels_with_features.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
"""
Add labels with features
========================
Display a labels layer with various features
.. tags:: layers, analysis
"""
import numpy as np
from skimage import data
from skimage.filters import threshold_otsu
from skimage.measure import label
from skimage.morphology import closing, remove_small_objects, square
from skimage.segmentation import clear_border
import napari
image = data.coins()[50:-50, 50:-50]
# apply threshold
thresh = threshold_otsu(image)
bw = closing(image > thresh, square(4))
# remove artifacts connected to image border
cleared = remove_small_objects(clear_border(bw), 20)
# label image regions
label_image = label(cleared)
# initialise viewer with coins image
viewer = napari.view_image(image, name='coins', rgb=False)
# get the size of each coin (first element is background area)
label_areas = np.bincount(label_image.ravel())[1:]
# split coins into small or large
size_range = max(label_areas) - min(label_areas)
small_threshold = min(label_areas) + (size_range / 2)
coin_sizes = np.where(label_areas > small_threshold, 'large', 'small')
label_features = {
'row': ['none']
+ ['top'] * 4
+ ['bottom'] * 4, # background is row: none
'size': ["none", *coin_sizes], # background is size: none
}
color = {1: 'white', 2: 'blue', 3: 'green', 4: 'red', 5: 'yellow'}
# add the labels
label_layer = viewer.add_labels(
label_image,
name='segmentation',
features=label_features,
color=color,
)
if __name__ == '__main__':
napari.run()