-
Notifications
You must be signed in to change notification settings - Fork 2
/
N5Read.pyscro
140 lines (116 loc) · 6.32 KB
/
N5Read.pyscro
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
import zarr
from pathlib import Path
import numpy as np
import dask.array as da
_container_extensions = ('.zarr', '.n5')
def split_path_at_container(path):
# check whether a path contains a valid file path to a container file, and if so which container format it is
result = None, None
pathobj = Path(path)
if pathobj.suffix in _container_extensions:
result = [path, '']
else:
for parent in pathobj.parents:
if parent.suffix in _container_extensions:
result = path.split(parent.suffix)
result[0] += parent.suffix
return result
def get_resolution_and_offset(dataset):
resolution = [1] * dataset.ndim
offset = [0] * dataset.ndim
attrs = dataset.attrs
if 'resolution' in attrs.keys() and 'offset' in attrs.keys():
# reverse the order to make it z,y,x
resolution = dataset.attrs['resolution'][::-1]
offset = dataset.attrs['offset'][::-1]
elif 'pixelResolution' in attrs.keys():
resolution = dataset.attrs['pixelResolution']['dimensions']
offset = [0] * len(resolution)
else:
print('Resolution and offset could not be determined from metadata. Using default: Resolution = {0} nm, Offset = {1} nm'.format(resolution, offset))
return resolution, offset
class N5Read(PyScriptObject):
def __init__(self):
self.data.valid_types = ['HxUniformScalarField3']
self.do_it = HxPortDoIt(self, 'read', 'Load N5')
self.input_dir = HxPortFilename(self, 'inputDir', 'Input Directory')
self.input_dir.mode = HxPortFilename.LOAD_DIRECTORY
self.info = HxPortInfo(self, 'array_info', 'Array info')
self.container = None
self.dataset = None
self.container_path = None
self.dataset_path = None
self.resolution = None
self.offset = None
self._dimensions = ('x', 'y', 'z')
self.slice_textboxes = dict()
self.update_info_box()
for dim in self._dimensions:
dim_disp = dim.upper()
self.slice_textboxes[dim] = HxPortIntTextN(self,
label='{0} limits'.format(dim_disp),
name='{0}_lims'.format(dim))
self.slice_textboxes[dim].texts = [HxPortIntTextN.IntText(label="Start",
value=0),
HxPortIntTextN.IntText(label="Stop",
value=0)]
self.slices = {d: slice(0, 1) for d in self._dimensions}
def update(self):
if self.input_dir.is_new and self.input_dir.filenames is not None:
self.container_path, self.dataset_path = split_path_at_container(self.input_dir.filenames)
if self.container_path is None:
hx_message.error(message='You have not selected a folder that represents an N5 array.')
return
self.container = self.access_container(mode='r')
self.dataset = self.container[self.dataset_path]
# validate that user selected a dataset
if not isinstance(self.dataset, zarr.core.Array):
hx_message.error(message='You have not selected a folder that represents an N5 array.')
return
self.resolution, self.offset = get_resolution_and_offset(self.dataset)
self.update_info_box()
for ind, dim in enumerate(self._dimensions):
for tb in self.slice_textboxes[dim].texts:
tb.clamp_range = (0, self.dataset.shape[::-1][ind])
assert len(self.dataset.shape) == 3
# if any of the textboxes have changed, then update the corresponding slices
if any(s.is_new for s in self.slice_textboxes.values()):
for d in self._dimensions:
self.slices[d] = slice(self.slice_textboxes[d].texts[0].value, self.slice_textboxes[d].texts[1].value)
pass
def update_info_box(self):
if isinstance(self.dataset, zarr.core.Array):
self.info.text = '{0} array with shape {1}'.format(self.dataset.dtype, self.dataset.shape[::-1])
else:
self.info.text = 'No array selected'
def access_container(self, mode):
container_extension = Path(self.container_path).suffix
store_path = None
if container_extension == '.n5':
store_path = zarr.N5Store(self.container_path)
elif container_extension == '.zarr':
store_path = self.container_path
container = zarr.open(store=store_path, mode=mode)
return container
def compute(self):
if not self.do_it.was_hit:
return
result = hx_project.create('HxUniformScalarField3')
slices_ = tuple(self.slices[d] for d in self._dimensions)[::-1]
array = da.from_array(self.container[self.dataset_path])[slices_].compute().T
shape_native_res = ((s-1) * r for s, r in zip(array.shape, self.resolution[::-1]))
# amira doesn't like numpy uint64 or uint32
if array.dtype in (np.dtype('uint64'), np.dtype('uint32')):
array = array.astype('uint16')
if array.dtype == np.dtype('int64'):
array = array.astype('int32')
# for a 3D array with dimensions numbered [0,1,2], amira assigns named dimensions ['x','y','z']
# so everything has to be flipped relative to the pythonic indexing scheme
# in amira, the bounding box defines the pixel size and position in space of the data. So we set the bounding box and origin in nanometers.
bbox_starts = tuple((r * s.start) + o for r, s, o in zip(self.resolution, slices_, self.offset))[::-1]
bbox_stops = tuple(o + s for o, s in zip(bbox_starts, shape_native_res))
result.bounding_box = bbox_starts, bbox_stops
result.set_array(array)
result.name = self.dataset_path
# connect the resulting 3D data to the zarr loader object
result.ports.master.connect(hx_project.get(self.name))