-
Notifications
You must be signed in to change notification settings - Fork 0
/
stackreg.py
executable file
·315 lines (252 loc) · 9.48 KB
/
stackreg.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
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
#!/usr/bin/env python3
import os
import re
import numpy as np
import pystackreg
import tifffile
import settings as s
def file_finder(path, pattern, nonrecursive=False):
files_list = [] # To store the paths of .txt files
# Walk through the directory and its subdirectories
for root, _, files in os.walk(path):
for filename in files:
if re.search(pattern, filename):
files_list.extend(
[filename[:-4]])
if nonrecursive:
break
return files_list
def transform(
img,
sr,
transform_matrix,
):
out = sr.transform_stack(img, tmats=transform_matrix)
out = out.astype(np.int16)
return out
def register(
img,
sr,
REFERENCE_FRAME,
NUMBER_OF_REF_FRAMES,
MOVING_AVERAGE,
TIME_AXIS,
verbose=False,
):
transform_matrix = sr.register_stack(
img,
reference=REFERENCE_FRAME,
n_frames=NUMBER_OF_REF_FRAMES,
moving_average=MOVING_AVERAGE,
axis=TIME_AXIS,
verbose=verbose,
)
return transform_matrix
def process(
file,
DIRECTORY=s.DIRECTORY,
DISTORTION_TYPE=s.DISTORTION_TYPE,
REFERENCE_FRAME=s.REFERENCE_FRAME,
NUMBER_OF_REF_FRAMES=s.NUMBER_OF_REF_FRAMES,
MOVING_AVERAGE=s.MOVING_AVERAGE,
TIME_AXIS=s.TIME_AXIS,
SPLIT_ONLY=s.SPLIT_ONLY,
REFERENCE_CHANNEL=s.REFERENCE_CHANNEL,
SAVE_TRANSFORM_MATRIX=s.SAVE_TRANSFORM_MATRIX,
READ_TRANSFORM_MATRIX=s.READ_TRANSFORM_MATRIX,
verbose=False,
):
match DISTORTION_TYPE:
case 'TRANSLATION': sr = pystackreg.StackReg(pystackreg.StackReg.TRANSLATION)
case 'RIGID_BODY': sr = pystackreg.StackReg(pystackreg.StackReg.RIGID_BODY)
case 'SCALED_ROTATION': sr = pystackreg.StackReg(pystackreg.StackReg.SCALED_ROTATION)
case 'AFFINE': sr = pystackreg.StackReg(pystackreg.StackReg.AFFINE)
case 'BILINEAR': sr = pystackreg.StackReg(pystackreg.StackReg.BILINEAR)
case _: sr = pystackreg.StackReg(pystackreg.StackReg.TRANSLATION)
metadata = {
' Current File': DIRECTORY + file + '_registered',
' Original File': DIRECTORY + file,
' Transformation Matrix Used': READ_TRANSFORM_MATRIX,
' Transformations Applied': not SPLIT_ONLY,
' Software Used': 'https://github.com/konung-yaropolk/stackreg',
' TIME_AXIS': TIME_AXIS,
' REFERENCE_CHANNEL': REFERENCE_CHANNEL,
' DISTORTION_TYPE': DISTORTION_TYPE,
' REFERENCE_FRAME': REFERENCE_FRAME,
' NUMBER_OF_REF_FRAMES': NUMBER_OF_REF_FRAMES,
' MOVING_AVERAGE': MOVING_AVERAGE,
}
# Bad construction, to review:
try:
img = tifffile.imread(DIRECTORY + file + '.tif')
except:
try:
img = tifffile.imread(DIRECTORY + file + '.tiff')
except Exception as e:
print('\n!!! ', DIRECTORY + file, '- File not found')
return e
try:
print('\n>>> ', file, '- started working with the file...')
# algorytm for 4-dimentional tiff:
if img.ndim == 4:
# Here is a bug - sometimes array shape must be (1, len(img[0]), 3, 0)
if READ_TRANSFORM_MATRIX:
transform_matrix = np.load(
DIRECTORY + file + '_transform_matrix.npy')
else:
transform_matrix_list = np.empty((1, len(img[0]), 4, 0))
# print(img.shape)
transform_matrix = np.array([])
if not SPLIT_ONLY: # Bad construction with SPLIT_ONLY, to review
for ch in range(len(img)):
if verbose:
print('\n Analyzing file:',
file, ', channel', ch + 1, '...')
if not READ_TRANSFORM_MATRIX:
transform_matrix_list = np.append(
transform_matrix_list,
[register(
img[ch],
sr,
REFERENCE_FRAME,
NUMBER_OF_REF_FRAMES,
MOVING_AVERAGE,
TIME_AXIS,
verbose=verbose,
)
],
axis=-1,
)
if not READ_TRANSFORM_MATRIX:
print(transform_matrix_list.shape)
transform_matrix = np.mean(
transform_matrix_list,
axis=0,
) if not REFERENCE_CHANNEL else transform_matrix_list[REFERENCE_CHANNEL-1]
if SAVE_TRANSFORM_MATRIX:
np.save(
DIRECTORY + file + '_transform_matrix',
transform_matrix,
allow_pickle=False,
fix_imports=True,
)
for ch in range(len(img)):
if not SPLIT_ONLY: # Bad construction with SPLIT_ONLY, to review
if verbose:
print('\n Transforming file',
file, ', channel', ch + 1, '...')
out = transform(
img[ch],
sr,
transform_matrix,
)
else:
out = img[ch]
tifffile.imwrite(
'{}{}_ch{}{}.tif'.format(
DIRECTORY,
file,
ch + 1,
'_registered' if not SPLIT_ONLY else ''
),
out,
imagej=True,
compression='zlib',
metadata=metadata,
)
# algorytm for 3-dimentional tiff:
elif img.ndim == 3 and not SPLIT_ONLY: # Bad construction with SPLIT_ONLY, to review
if READ_TRANSFORM_MATRIX:
transform_matrix = np.load(
DIRECTORY + file + '_transform_matrix.npy')
print('Transform matrix found for this file')
else:
transform_matrix = np.array([])
transform_matrix = register(
img,
sr,
REFERENCE_FRAME,
NUMBER_OF_REF_FRAMES,
MOVING_AVERAGE,
TIME_AXIS,
verbose=False,
)
if SAVE_TRANSFORM_MATRIX:
np.save(
DIRECTORY + file + '_transform_matrix',
transform_matrix,
allow_pickle=False,
fix_imports=True,
)
out = transform(
img,
sr,
transform_matrix,
)
if verbose:
print('\n Writing to file...')
tifffile.imwrite(
'{}{}_registered.tif'.format(
DIRECTORY,
file,
),
out,
imagej=True,
compression='zlib',
metadata=metadata,
)
elif img.ndim == 3 and SPLIT_ONLY == True:
raise Exception(
'SPLIT_ONLY option is activated, there is nothing to do with single-channel image file')
else:
raise Exception('Wrong TIFF format, or check TIME_AXIS parameter')
except Exception as e:
print('!!! An error occured when processing {}:\n{}'.format(file, e))
return e
else:
print('\n<<< ', file, '- File done!')
# immediatly clearing memory used by np arrays
finally:
img = None
del img
transform_matrix_list = None
del transform_matrix_list
transform_matrix = None
del transform_matrix
out = None
del out
def main():
if s.TAKE_ALL_FILES:
TODO_LIST = file_finder(s.DIRECTORY, r'.*\.tif')
else:
TODO_LIST = s.TODO_LIST
if s.MULTIPROCESSING:
import multiprocessing as mp
cores = mp.cpu_count() # CPU cores count
files = len(TODO_LIST) # Files to do count
processes_limit = s.PROCESSES_LIMIT if s.PROCESSES_LIMIT else 100
processes = min(cores, files,
processes_limit)
try:
pool = mp.Pool(processes)
except ValueError:
print('No one file listed, there is nothing to do.')
return 0
print('\nParallel processing mode activated:')
print('Please, ensure if you have enough RAM for multiprocessing.')
print('If processing went wrong, please, use PROCESSES_LIMIT option in the settings.py')
print('{0} cpu cores per queue of {1} files found, pool of {2} processes created.'.format(
cores, files, processes))
results = [pool.apply_async(process, args=(line[0],) if isinstance(line, list) else (
line,), kwds=line[1] if isinstance(line, list) else {}) for line in TODO_LIST]
output = [p.get() for p in results]
print('\nErrors:', output)
else:
for line in TODO_LIST:
if isinstance(line, list):
process(line[0], **line[1], verbose=True)
else:
process(line, verbose=True)
print('\nSeries done!\n')
if __name__ == '__main__':
main()