[3b7fea]: / seg_crop_pad_scale.py

Download this file

446 lines (347 with data), 15.8 kB

  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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
#!/usr/bin/env python3
"""
Author : briancottle <briancottle@localhost>
Date : 2023-01-02
Purpose: Cropping, padding, and scaling segmentations in preparation for 3D modeling
"""
import argparse
from typing import NamedTuple
import numpy as np
import cv2 as cv
import os
import matplotlib.pyplot as plt
import tqdm
from natsort import natsorted
from glob import glob
import magic
import re
from PIL import Image
class Args(NamedTuple):
""" Command-line arguments """
tissue_chainID: str
cropping: bool
old_files: bool
fid_seg: bool
node_seg: bool
unet_seg: bool
high_res_seg: bool
node_white: bool
fid_white: bool
reduction_size: int
# --------------------------------------------------
def get_args() -> Args:
""" Get command-line arguments """
parser = argparse.ArgumentParser(
description='Cropping, padding, and scaling segmentations in preparation for 3D modeling',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-t_id',
'--tissue_chainID',
type=str,
metavar='chainID',
help='ID used to identify where the tissue files are stored')
parser.add_argument('-c',
'--cropping',
help='Boolean: Do you need to crop the uNet dataset first?',
action='store_true')
parser.add_argument('-o',
'--old_files',
help='Is the dataset of interest from the old set?',
action='store_true')
parser.add_argument('-f',
'--fid_seg',
help='Do you want to process the fiduciary segmentations?',
action='store_true')
parser.add_argument('-n',
'--node_seg',
help='Do you want to process the nodal segmentations?',
action='store_true')
parser.add_argument('-u',
'--unet_seg',
help='Do you want to process the uNet segmentations?',
action='store_true')
parser.add_argument('-d',
'--high_res_seg',
help='Do you want to process the high_res segmentations?',
action='store_true')
parser.add_argument('-i',
'--node_white',
help='Is the segmentation for the node inverted?',
action='store_true')
parser.add_argument('-j',
'--fid_white',
help='Is the segmentation for the fiduciary inverted?',
action='store_true')
parser.add_argument('-r',
'--reduction_size',
help='what scalar to use for reducing the size(4 or 8), default is 4',
metavar='int',
type=int,
default=4)
args = parser.parse_args()
return Args(args.tissue_chainID,
args.cropping,
args.old_files,
args.fid_seg,
args.node_seg,
args.unet_seg,
args.high_res_seg,
args.node_white,
args.fid_white,
args.reduction_size)
# --------------------------------------------------
def main() -> None:
""" Make a jazz noise here """
args = get_args()
TissueChainID = args.tissue_chainID
cropping = args.cropping
old_files = args.old_files
fiduciary_files = args.fid_seg
nodal_files = args.node_seg
seg_files = args.unet_seg
high_res_files = args.high_res_seg
nodal_white = args.node_white
fiduciary_white = args.fid_white
reduction_size = args.reduction_size
if reduction_size == 4:
reduction_name = 'QuarterScale'
if reduction_size == 8:
reduction_name = 'EighthScale'
base_directory = '/var/confocaldata/HumanNodal/HeartData/'+ TissueChainID
JPG_directory = '/var/confocaldata/HumanNodal/HeartData/'+ TissueChainID +'JPG/'
jpg_file_names = glob(JPG_directory + '*.jpg')
if old_files:
ML_directory = '/var/confocaldata/HumanNodal/HeartData/'+ TissueChainID +'uNet_Segmentations/'
Nodal_Seg_directory = '/var/confocaldata/HumanNodal/HeartData/'+ TissueChainID +'Segmentations/Nodal Segmentation FullScale_NoPad/'
if fiduciary_files:
Fiduciary_Seg_directory = '/var/confocaldata/HumanNodal/HeartData/'+ TissueChainID +'Segmentations/Fiduciary Segmentation FullScale_NoPad/'
else:
ML_directory = '/var/confocaldata/HumanNodal/HeartData/'+ TissueChainID +'uNet_Segmentations/'
Nodal_Seg_directory = '/var/confocaldata/HumanNodal/HeartData/'+ TissueChainID +'Segmentations/Nodal Segmentation/'
if fiduciary_files:
Fiduciary_Seg_directory = '/var/confocaldata/HumanNodal/HeartData/'+ TissueChainID +'Segmentations/Fiduciary Segmentation/'
high_res_directory = '/var/confocaldata/HumanNodal/HeartData/'+ TissueChainID +'HighResSeg/'
os.chdir(ML_directory)
jpg_file_names = natsorted(jpg_file_names)
padding_size = 4000 # + 1536
# %% USE THIS SECTION FOR CROPPING THE SEGMENTATIONS AFTER THE UNET HAS AT IT
if cropping:
for idx in tqdm.tqdm(range(len(jpg_file_names))):
out_directory = './../Cropped_uNet_Segmentations/'
# create the directory for saving if it doesn't already exist
if not os.path.isdir(out_directory):
os.mkdir(out_directory)
os.chdir(out_directory)
jpg_file = jpg_file_names[idx]
id = jpg_file.split('/')[-1].split('.')[0]
id = id.split('_')[0] + '_' + id.split('_')[1] + '_' + id.split('_')[2]
ml_file = glob(ML_directory + f'{id}_*.png')[0]
jpg_image1 = cv.imread(jpg_file)
ml_image1 = cv.imread(ml_file)[:,:,0]
[x,y,z] = jpg_image1.shape
cropped_ml1 = ml_image1[padding_size:padding_size+x,
padding_size:padding_size+y]
cv.imwrite(
id +
f'_CroppedSeg.png',
cropped_ml1
)
# %%
ML_directory = '/var/confocaldata/HumanNodal/HeartData/'+ TissueChainID +'Cropped_uNet_Segmentations/'
ml_file_names = glob(ML_directory + '*.png')
all_image_sizes = []
for file_name in ml_file_names:
header = magic.from_file(file_name)
size = re.search('(\d+) x (\d+)',header).groups()
sizes = [int(a) for a in size]
all_image_sizes.append(sizes)
max_width = np.max(np.asarray(all_image_sizes)[:,0])
max_height = np.max(np.asarray(all_image_sizes)[:,1])
idx = 200
additional_padding = 4000
os.chdir(JPG_directory)
out_big_directory = base_directory + 'Padded_Images/'
out_small_directory = base_directory + 'Padded_Images_' + reduction_name + '/'
out_parent_list = [out_big_directory,out_small_directory]
out_list = []
if not os.path.isdir(out_big_directory):
os.mkdir(out_big_directory)
if not os.path.isdir(out_small_directory):
os.mkdir(out_small_directory)
for idx, out_directory in enumerate(out_parent_list):
jpg_out = out_directory + 'JPG'
seg_out = out_directory + 'Seg'
nodal_out = out_directory + 'Nodal'
fiduciary_out = out_directory + 'Fiduciary'
high_res_out = out_directory + 'HighRes'
out_list.append([jpg_out,seg_out,nodal_out,high_res_out,fiduciary_out])
for directory in out_list[idx]:
if not os.path.isdir(directory):
os.mkdir(directory)
for idx in tqdm.tqdm(range(len(jpg_file_names))):
jpg_file = jpg_file_names[idx]
id = jpg_file.split('/')[-1].split('.')[0]
id = id.split('_')[0] + '_' + id.split('_')[1] + '_' + id.split('_')[2]
# Create a separate section for the nodal tissue stuff, as it looks like
# nodal segmentation will actually happen after the registration using the
# segmentations
# change this to _*.png if you are not using the FullScale_NoPad segmentations
# will need to scale the segmentations for newer segmentations that haven't been
# performed using previously padded images. This section is below, starting with
jpg_image = cv.imread(jpg_file)
[height,width,z] = jpg_image.shape
height_diff = max_height - height
width_diff = max_width - width
if height_diff%2 == 1:
pad_top = np.floor(height_diff/2) + additional_padding
pad_bottom = np.floor(height_diff/2) + additional_padding
pad_bottom += 1
else:
pad_top = np.floor(height_diff/2) + additional_padding
pad_bottom = np.floor(height_diff/2) + additional_padding
if width_diff%2 == 1:
pad_left = np.floor(width_diff/2) + additional_padding
pad_right = np.floor(width_diff/2) + additional_padding
pad_right += 1
else:
pad_left = np.floor(width_diff/2) + additional_padding
pad_right = np.floor(width_diff/2) + additional_padding
padded_jpg = cv.copyMakeBorder(jpg_image,
int(pad_top),
int(pad_bottom),
int(pad_left),
int(pad_right),
borderType=cv.cv2.BORDER_CONSTANT,
value=[255,255,255])
os.chdir(out_list[0][0])
cv.imwrite(
id +
f'_Padded.png',
padded_jpg
)
[pad_height,pad_width,z] = padded_jpg.shape
width_small = int(pad_width/reduction_size)
height_small = int(pad_height/reduction_size)
jpg_small = cv.resize(padded_jpg,[width_small,height_small],cv.INTER_AREA)
os.chdir(out_list[1][0])
cv.imwrite(
id +
f'_Padded_' + reduction_name + '.png',
jpg_small
)
if seg_files:
ml_file = glob(ML_directory + f'{id}_*.png')[0]
ml_image = cv.imread(ml_file)[:,:,0]
padded_seg = cv.copyMakeBorder(ml_image,
int(pad_top),
int(pad_bottom),
int(pad_left),
int(pad_right),
borderType=cv.cv2.BORDER_CONSTANT,
value=[0,0,0])
os.chdir(out_list[0][1])
cv.imwrite(
id +
f'_Padded_Seg.png',
padded_seg
)
seg_small = np.array(Image.fromarray(padded_seg).resize((width_small,height_small), Image.NEAREST))
os.chdir(out_list[1][1])
cv.imwrite(
id +
f'_Padded_Seg_' + reduction_name + '.png',
seg_small
)
if nodal_files:
if old_files:
nodal_file = glob(Nodal_Seg_directory + f'{id}-*.png')[0]
else:
nodal_file = glob(Nodal_Seg_directory + f'{id}_*.png')[0]
nodal_image = cv.imread(nodal_file)[:,:,0]
# be warry of this, you may need to use this later, though I'm not sure what
# it was originally used for.
if nodal_white:
if sum(sum(nodal_image)) > 0:
nodal_image = ~nodal_image
# This accounts for the nodal segmentation images being a quarter the
# original size, but you should make sure that you haven't already done the
# fullscale noPad stuff yet
if ~old_files:
nodal_image = np.array(Image.fromarray(nodal_image).resize((width,height), Image.NEAREST))
padded_nodal = cv.copyMakeBorder(nodal_image,
int(pad_top),
int(pad_bottom),
int(pad_left),
int(pad_right),
borderType=cv.cv2.BORDER_CONSTANT,
value=[0,0,0])
os.chdir(out_list[0][2])
cv.imwrite(
id +
f'_Padded_Nodal.png',
padded_nodal
)
nodal_small = np.array(Image.fromarray(padded_nodal).resize((width_small,height_small), Image.NEAREST))
os.chdir(out_list[1][2])
cv.imwrite(
id +
f'_Padded_Nodal_' + reduction_name + '.png',
nodal_small
)
if high_res_files:
high_res_file = glob(high_res_directory + f'{id}_*.png')[0]
high_res_image = cv.imread(high_res_file)[:,:,0]
padded_high_res = cv.copyMakeBorder(high_res_image,
int(pad_top),
int(pad_bottom),
int(pad_left),
int(pad_right),
borderType=cv.cv2.BORDER_CONSTANT,
value=[0,0,0])
os.chdir(out_list[0][3])
cv.imwrite(
id +
f'_Padded_HighRes.png',
padded_high_res
)
high_res_small = np.array(Image.fromarray(padded_high_res).resize((width_small,height_small), Image.NEAREST))
os.chdir(out_list[1][3])
cv.imwrite(
id +
f'_Padded_HighRes_' + reduction_name + '.png',
high_res_small
)
if fiduciary_files:
if old_files:
fiduciary_file = glob(Fiduciary_Seg_directory + f'{id}-*.png')[0]
else:
fiduciary_file = glob(Fiduciary_Seg_directory + f'{id}_*.png')[0]
fiduciary_image = cv.imread(fiduciary_file)[:,:,0]
if fiduciary_white:
if sum(sum(fiduciary_image)) > 0:
fiduciary_image = ~fiduciary_image
if ~old_files:
fiduciary_image = np.array(Image.fromarray(fiduciary_image).resize((width,height), Image.NEAREST))
padded_fiduciary = cv.copyMakeBorder(fiduciary_image,
int(pad_top),
int(pad_bottom),
int(pad_left),
int(pad_right),
borderType=cv.cv2.BORDER_CONSTANT,
value=[0,0,0])
os.chdir(out_list[0][4])
cv.imwrite(
id +
f'_Padded_Fiduciary.png',
padded_fiduciary
)
fiduciary_small = np.array(Image.fromarray(padded_fiduciary).resize((width_small,height_small), Image.NEAREST))
os.chdir(out_list[1][4])
cv.imwrite(
id +
f'_Padded_Fiduciary_' + reduction_name + '.png',
fiduciary_small
)
# %%
# --------------------------------------------------
if __name__ == '__main__':
main()