-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdataloader.py
1051 lines (865 loc) · 38.8 KB
/
dataloader.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
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# dataloader for fastmri dataset
import os
import logging
import pathlib
import random
import shutil
import time
import h5py
import cv2
import pdb
import numpy as np
import torch
from util import Get_sobel
from torch.utils.data import DataLoader
from fastmri.data import transforms_simple as transforms
from torch.utils.data import Dataset
from cardiac_dataloader import SliceData_cardiac
from cc359_multicoil_dataloader import SliceData_cc359_multicoil
class MaskFunc:
"""
Cartesian masking
MaskFunc creates a sub-sampling mask of a given shape.
The mask selects a subset of columns from the input k-space data. If the k-space data has N
columns, the mask picks out:
1. N_low_freqs = (N * center_fraction) columns in the center corresponding to
low-frequencies
2. The other columns are selected uniformly at random with a probability equal to:
prob = (N / acceleration - N_low_freqs) / (N - N_low_freqs).
This ensures that the expected number of columns selected is equal to (N / acceleration)
It is possible to use multiple center_fractions and accelerations, in which case one possible
(center_fraction, acceleration) is chosen uniformly at random each time the MaskFunc object is
called.
For example, if accelerations = [4, 8] and center_fractions = [0.08, 0.04], then there
is a 50% probability that 4-fold acceleration with 8% center fraction is selected and a 50%
probability that 8-fold acceleration with 4% center fraction is selected.
"""
def __init__(self, center_fractions, accelerations):
"""
Args:
center_fractions (List[float]): Fraction of low-frequency columns to be retained.
If multiple values are provided, then one of these numbers is chosen uniformly
each time.
accelerations (List[int]): Amount of under-sampling. This should have the same length
as center_fractions. If multiple values are provided, then one of these is chosen
uniformly each time. An acceleration of 4 retains 25% of the columns, but they may
not be spaced evenly.
"""
if len(center_fractions) != len(accelerations):
raise ValueError('Number of center fractions should match number of accelerations')
self.center_fractions = center_fractions
self.accelerations = accelerations
self.rng = np.random.RandomState()
def __call__(self, shape, seed=None):
"""
Args:
shape (iterable[int]): The shape of the mask to be created. The shape should have
at least 3 dimensions. Samples are drawn along the second last dimension.
seed (int, optional): Seed for the random number generator. Setting the seed
ensures the same mask is generated each time for the same shape.
Returns:
torch.Tensor: A mask of the specified shape.
"""
# shape (1, H, W, 2) for multicoil and (1, W, 2) for single coil
if len(shape) < 3:
raise ValueError('Shape should have 3 or more dimensions')
self.rng.seed(seed)
num_rows, num_cols = shape[-3], shape[-2]
choice = self.rng.randint(0, len(self.accelerations))
center_fraction = self.center_fractions[choice]
acceleration = self.accelerations[choice]
# Create the mask
num_low_freqs = int(round(num_cols * center_fraction))
prob = (num_cols / acceleration - num_low_freqs) / (num_cols - num_low_freqs)
mask = self.rng.uniform(size=num_cols) < prob
pad = (num_cols - num_low_freqs + 1) // 2
mask[pad:pad + num_low_freqs] = True
# Reshape the mask
'''
mask_shape = [1 for _ in shape]
mask_shape[-2] = num_cols
mask = torch.from_numpy(mask.reshape(*mask_shape).astype(np.float32))
'''
shape[-1] = 1
mask_out = np.ones(shape) #(1, H, W, 1) or (H, W, 1)
if len(shape) == 4:
mask_prod = np.zeros((1, 1, num_cols, 1))
mask_prod[0,0,:,0] = mask
else:
mask_prod = np.zeros((1, num_cols, 1))
mask_prod[0,:,0] = mask
mask_out = mask_out * mask_prod
return mask_out #(1, H, W, 1) or (H, W, 1)
class SliceData_fastmri(Dataset):
"""
slice dataset for fastmri singlecoil and multicoil
"""
def __init__(self,
root,
transform,
challenge,
dataMode='complex',
sample_rate=1,
skip_head=0,
use_sens_map=0):
"""
Args:
root (pathlib.Path): Path to the dataset.
transform (callable): A callable object that pre-processes the raw data into
appropriate form. The transform function should take 'kspace', 'target',
'attributes', 'filename', and 'slice' as inputs. 'target' may be null
for test data.
challenge (str): "singlecoil" or "multicoil" depending on which challenge to use.
sample_rate (float, optional): A float between 0 and 1. This controls what fraction of the volumes should be loaded.
skip_head: whether skip the first few bad images
"""
if challenge not in ('singlecoil', 'multicoil'):
raise ValueError('challenge should be either "singlecoil" or "multicoil"')
self.transform = transform
self.use_sens_map = use_sens_map
self.recons_key = 'reconstruction_esc' if challenge == 'singlecoil' else 'reconstruction_rss'
self.dataMode = dataMode
self.examples = []
files = list(pathlib.Path(root).iterdir())
if use_sens_map:
sens_root= root.rstrip('/') + '_sensitivity_no_crop/'
if not os.path.exists(sens_root):
assert True, "do not exists sensitivity map"
if sample_rate < 1:
random.shuffle(files)
num_files = round(len(files) * sample_rate)
files = files[:num_files]
for fname in sorted(files):
name1 = fname.name
kspace = h5py.File(fname, 'r')['kspace'] #(num_slices, height, width)
num_slices = kspace.shape[0]
if skip_head:
begin = num_slices // 2 - 8
else:
begin = 0
if use_sens_map:
fname_sens = os.path.join(sens_root, name1)
self.examples += [(fname,fname_sens,slice) for slice in range(begin, num_slices)]
else:
self.examples += [(fname,None,slice) for slice in range(begin, num_slices)]
def __len__(self):
return len(self.examples)
def __getitem__(self, i):
fname, fname_sens, slice = self.examples[i]
if 'edge' in self.dataMode:
compute_edge = 1
else:
compute_edge = 0
# read in kspace data
with h5py.File(fname, 'r') as data:
kspace = data['kspace'][slice]
target = data[self.recons_key][slice] if self.recons_key in data else None
maxval = data.attrs['max'].astype(np.float32)
# sensitivity map
if self.use_sens_map:
assert fname_sens is not None, "Do not have root for the sensitivity map!"
with h5py.File(fname_sens, 'r') as data1:
sens_map = np.array(data1['sens_maps'][slice]) #(H, W, coils)
else:
sens_map = None
return self.transform(kspace, target, maxval, fname.name, slice, sens_map, compute_edge=compute_edge)
class SliceData_cc359(Dataset):
"""
A PyTorch Dataset that provides access to MR image slices for cc359 single coil
"""
def __init__(self, root, transform, sample_rate=1, skip_head=0):
"""
Args:
root (pathlib.Path): Path to the dataset.
transform (callable): A callable object that pre-processes the raw data into
appropriate form. The transform function should take 'kspace', 'target',
'attributes', 'filename', and 'slice' as inputs. 'target' may be null
for test data.
challenge (str): "singlecoil" or "multicoil" depending on which challenge to use.
sample_rate (float, optional): A float between 0 and 1. This controls what fraction
of the volumes should be loaded.
"""
self.transform = transform
self.examples = []
files = list(pathlib.Path(root).iterdir())
if sample_rate < 1:
random.shuffle(files)
num_files = round(len(files) * sample_rate)
files = files[:num_files]
for fname in sorted(files):
im = np.load(fname) #(num_slices, height, width, 2)
num_slices = im.shape[0]
if skip_head:
begin = num_slices // 2 - 8
else:
begin = 0
self.examples += [(fname, slice) for slice in range(begin, num_slices)]
def __len__(self):
return len(self.examples)
def __getitem__(self, i):
fname, slice = self.examples[i]
im = np.load(fname)
kspace = im[slice]
maxval = 0
return self.transform(kspace, maxval, fname.name, slice)
#======================================================================================
# DataTransform
class DataTransform_real_fastmri:
"""
Data Transformer for training fastmri single-coild real-valued image
"""
def __init__(self, mask_func, resolution, which_challenge, use_seed=True):
"""
Args:
mask_func (common.subsample.MaskFunc): A function that can create a mask of
appropriate shape.
resolution (int): Resolution of the image.
which_challenge (str): Either "singlecoil" or "multicoil" denoting the dataset.
use_seed (bool): If true, this class computes a pseudo random number generator seed
from the filename. This ensures that the same mask is used for all the slices of
a given volume every time.
"""
if which_challenge not in ('singlecoil', 'multicoil'):
raise ValueError(f'Challenge should either be "singlecoil" or "multicoil"')
self.mask_func = mask_func
self.resolution = resolution
self.which_challenge = which_challenge
self.use_seed = use_seed
def __call__(self, kspace, target, attrs, fname, slice, sens_map=None, compute_edge=False):
"""
Args:
kspace (numpy.array): Input k-space of shape (num_coils, rows, cols, 2) for multi-coil
data or (rows, cols, 2) for single coil data.
target (numpy.array): Target image
attrs (dict): Acquisition related information stored in the HDF5 object.
fname (str): File name
slice (int): Serial number of the slice.
Returns:
(tuple): tuple containing:
image (torch.Tensor): Zero-filled input image.
target (torch.Tensor): Target image converted to a torch Tensor.
mean (float): Mean value used for normalization.
std (float): Standard deviation value used for normalization.
norm (float): L2 norm of the entire volume.
"""
seed = None if not self.use_seed else tuple(map(ord, fname))
# target
target = transforms.to_tensor(target)
kspace = transforms.to_tensor(kspace)
# get masked kspace
masked_kspace, mask = transforms.apply_mask(kspace, self.mask_func, seed)
# get zim
zim = transforms.ifft2(masked_kspace)
zim = transforms.complex_center_crop(zim, (self.resolution, self.resolution))
zim = transforms.complex_abs(zim)
if self.which_challenge == 'multicoil':
zim = transforms.root_sum_of_squares(zim)
zim, mean, std = transforms.normalize_instance(zim, eps=1e-11)
zim= zim.clamp(-6, 6)
# normalize target
target = transforms.normalize(target, mean, std, eps=1e-11)
target = target.clamp(-6, 6)
return zim.unsqueeze(0), target, zim, zim, mean, std, attrs['max'].astype(np.float32), fname, slice
class DataTransform_complex_fastmri:
"""
Data Transformer for fastmri single coil
"""
def __init__(self, mask_func, resolution, which_challenge, use_seed=True):
"""
Args:
mask_func (common.subsample.MaskFunc): A function that can create a mask of
appropriate shape.
resolution (int): Resolution of the image.
which_challenge (str): Either "singlecoil" or "multicoil" denoting the dataset.
use_seed (bool): If true, this class computes a pseudo random number generator seed
from the filename. This ensures that the same mask is used for all the slices of
a given volume every time.
"""
if which_challenge not in ('singlecoil', 'multicoil'):
raise ValueError(f'Challenge should either be "singlecoil" or "multicoil"')
self.mask_func = mask_func
self.resolution = resolution
self.which_challenge = which_challenge
self.use_seed = use_seed
def __call__(self, kspace, target, attrs, fname, slice, sens_map=None, compute_edge=False):
"""
Args:
kspace (numpy.array): Input k-space of shape (num_coils, rows, cols, 2) for multi-coil
data or (rows, cols, 2) for single coil data.
target (numpy.array): Target image
attrs (dict): Acquisition related information stored in the HDF5 object.
fname (str): File name
slice (int): Serial number of the slice.
Returns:
(tuple): tuple containing:
image (torch.Tensor): Zero-filled input image.
target (torch.Tensor): Target image converted to a torch Tensor.
mean (float): Mean value used for normalization.
std (float): Standard deviation value used for normalization.
norm (float): L2 norm of the entire volume.
"""
seed = None if not self.use_seed else tuple(map(ord, fname))
# full kspace
full_kspace = transforms.to_tensor(kspace)
# target
target = transforms.to_tensor(target)
# crop kspace
kspace_crop = transforms.fft2(transforms.complex_center_crop(transforms.ifft2(full_kspace), (self.resolution, self.resolution)))
# scaling
kspace_crop *= 1e6
masked_kspace, mask = transforms.apply_mask(kspace_crop, self.mask_func, seed)
# zero-filled
zim = transforms.ifft2(masked_kspace)
zim_abs = transforms.complex_abs(zim)
_, mean, std = transforms.normalize_instance(zim_abs, eps=1e-11)
# scaling
target = target * 1e6
# reshape
zim = zim.permute(2,0,1)
return zim, target, masked_kspace, mask, mean, std, attrs['max'].astype(np.float32), fname, slice
class DataTransform_complex_fastmri_multicoil_vsnet:
"""
Data Transformer for fasmri multicoil
multicoil
"""
def __init__(self, mask_func, resolution, which_challenge, use_seed=True):
"""
Args:
mask_func (common.subsample.MaskFunc): A function that can create a mask of
appropriate shape.
resolution (int): Resolution of the image.
which_challenge (str): Either "singlecoil" or "multicoil" denoting the dataset.
use_seed (bool): If true, this class computes a pseudo random number generator seed
from the filename. This ensures that the same mask is used for all the slices of
a given volume every time.
"""
if which_challenge not in ('multicoil'):
raise ValueError(f'Challenge should "multicoil"')
self.mask_func = mask_func
self.resolution = resolution
self.which_challenge = which_challenge
self.use_seed = use_seed
def __call__(self, kspace, target, maxval, fname, slice, sens_map=None, compute_edge=False):
"""
Args:
kspace (numpy.array): Input k-space of shape (num_coils, rows, cols, 2) for multi-coil
data or (rows, cols, 2) for single coil data.
target (numpy.array): Target image
maxval: max val of the volume
fname (str): File name
slice (int): Serial number of the slice.
Returns:
(tuple): tuple containing:
image (torch.Tensor): Zero-filled input image.
target (torch.Tensor): Target image converted to a torch Tensor.
mean (float): Mean value used for normalization.
std (float): Standard deviation value used for normalization.
norm (float): L2 norm of the entire volume.
"""
seed = None if not self.use_seed else tuple(map(ord, fname))
# full kspace (coils, H, W, 2)
full_kspace = transforms.to_tensor(kspace) #(num_coils, rows, cols, 2)
shape1 = full_kspace.shape
# target (H, W)
target = transforms.to_tensor(target) #(rows, cols)
# use sens_map (H, W, coils, 2)
if sens_map is not None:
sens_map_out = np.zeros((shape1[1], shape1[2], shape1[0], 2))
sens_map_out[:,:,:,0] = sens_map.real
sens_map_out[:,:,:,1] = sens_map.imag
sens_map_out = torch.from_numpy(sens_map_out).permute(2,0,1,3).contiguous() #(coils, H, W, 2)
else:
sens_map_out = -1
# kspace crop (coils, 320, 320, 2)
#kspace_crop = transforms.fft2(transforms.complex_center_crop(transforms.ifft2(full_kspace, shift=True), (self.resolution, self.resolution)), shift=True)
kspace_crop = full_kspace
# scaling
kspace_crop *= 1e6
masked_kspace, mask = transforms.apply_mask(kspace_crop, self.mask_func, seed) #(num_coils, rows, cols, 2), (1,rows,cols,1)
# zero-filled
zim = transforms.ifft2(masked_kspace, shift=True) #(num_coils, rows, cols, 2)
# scaling
target = target * 1e6
# true edge
if compute_edge:
target_normal = (255*(target - target.min()))/(target.max().item() - target.min().item())
gt_edge = torch.from_numpy(Get_sobel(target_normal.numpy())) # (H, W)
gt_edge = gt_edge / gt_edge.max() # normalize
else:
gt_edge = -1
output = {
'zf':zim,
'gt':target,
'subF':masked_kspace,
'mask':mask,
'mean': 0,
'std': 1,
'fname':fname,
'slice_id': slice,
'maxval': maxval,
'gt_edge':gt_edge,
'sens_map': sens_map_out
}
return output
class DataTransform_complex_fastmri_multicoil:
"""
Data Transformer for fasmri multicoil
multicoil
"""
def __init__(self, mask_func, resolution, which_challenge, use_seed=True):
"""
Args:
mask_func (common.subsample.MaskFunc): A function that can create a mask of
appropriate shape.
resolution (int): Resolution of the image.
which_challenge (str): Either "singlecoil" or "multicoil" denoting the dataset.
use_seed (bool): If true, this class computes a pseudo random number generator seed
from the filename. This ensures that the same mask is used for all the slices of
a given volume every time.
"""
if which_challenge not in ('multicoil'):
raise ValueError(f'Challenge should "multicoil"')
self.mask_func = mask_func
self.resolution = resolution
self.which_challenge = which_challenge
self.use_seed = use_seed
def __call__(self, kspace, target, maxval, fname, slice, sens_map=None, compute_edge=False):
"""
Args:
kspace (numpy.array): Input k-space of shape (num_coils, rows, cols, 2) for multi-coil
data or (rows, cols, 2) for single coil data.
target (numpy.array): Target image
maxval: max val of the volume
fname (str): File name
slice (int): Serial number of the slice.
Returns:
(tuple): tuple containing:
image (torch.Tensor): Zero-filled input image.
target (torch.Tensor): Target image converted to a torch Tensor.
mean (float): Mean value used for normalization.
std (float): Standard deviation value used for normalization.
norm (float): L2 norm of the entire volume.
"""
seed = None if not self.use_seed else tuple(map(ord, fname))
# full kspace (coils, H, W, 2)
full_kspace = transforms.to_tensor(kspace) #(num_coils, rows, cols, 2)
COIL = full_kspace.shape[0]
# target (H, W)
target = transforms.to_tensor(target) #(rows, cols)
# use sens_map (H, W, coils, 2)
if sens_map is not None:
sens_map_out = np.zeros((320, 320, COIL, 2))
sens_map_out[:,:,:,0] = sens_map.real
sens_map_out[:,:,:,1] = sens_map.imag
sens_map_out = torch.from_numpy(sens_map_out).permute(2,0,1,3).contiguous() #(coils, H, W, 2)
else:
sens_map_out = -1
# kspace crop (coils, 320, 320, 2)
kspace_crop = transforms.fft2(transforms.complex_center_crop(transforms.ifft2(full_kspace, shift=True), (self.resolution, self.resolution)), shift=True)
# scaling
kspace_crop *= 1e6
masked_kspace, mask = transforms.apply_mask(kspace_crop, self.mask_func, seed) #(num_coils, rows, cols, 2), (1,rows,cols,1)
# zero-filled
zim = transforms.ifft2(masked_kspace, shift=True) #(num_coils, rows, cols, 2)
# scaling
target = target * 1e6
# true edge
if compute_edge:
target_normal = (255*(target - target.min()))/(target.max().item() - target.min().item())
gt_edge = torch.from_numpy(Get_sobel(target_normal.numpy())) # (H, W)
gt_edge = gt_edge / gt_edge.max() # normalize
else:
gt_edge = -1
output = {
'zf':zim,
'gt':target,
'subF':masked_kspace,
'mask':mask,
'mean': 0,
'std': 1,
'fname':fname,
'slice_id': slice,
'maxval': maxval,
'gt_edge':gt_edge,
'sens_map': sens_map_out
}
return output
class DataTransform_complex_fastmri_edge:
"""
Data Transformer for training fastmri edge
provide different edge extract for different gaussian smoothing
"""
def __init__(self, mask_func, resolution, which_challenge, use_seed=True):
"""
Args:
mask_func (common.subsample.MaskFunc): A function that can create a mask of
appropriate shape.
resolution (int): Resolution of the image.
which_challenge (str): Either "singlecoil" or "multicoil" denoting the dataset.
use_seed (bool): If true, this class computes a pseudo random number generator seed
from the filename. This ensures that the same mask is used for all the slices of
a given volume every time.
"""
if which_challenge not in ('singlecoil', 'multicoil'):
raise ValueError(f'Challenge should either be "singlecoil" or "multicoil"')
self.mask_func = mask_func
self.resolution = resolution
self.which_challenge = which_challenge
self.use_seed = use_seed
def __call__(self, kspace, target, attrs, fname, slice, sens_map=None):
"""
Args:
kspace (numpy.array): Input k-space of shape (num_coils, rows, cols, 2) for multi-coil
data or (rows, cols, 2) for single coil data.
target (numpy.array): Target image
attrs (dict): Acquisition related information stored in the HDF5 object.
fname (str): File name
slice (int): Serial number of the slice.
Returns:
(tuple): tuple containing:
image (torch.Tensor): Zero-filled input image.
target (torch.Tensor): Target image converted to a torch Tensor.
mean (float): Mean value used for normalization.
std (float): Standard deviation value used for normalization.
norm (float): L2 norm of the entire volume.
"""
seed = None if not self.use_seed else tuple(map(ord, fname))
# full kspace
full_kspace = transforms.to_tensor(kspace)
# target
target = transforms.to_tensor(target)
# crop kspace
kspace_crop = transforms.fft2(transforms.complex_center_crop(transforms.ifft2(full_kspace), (self.resolution, self.resolution)))
# scaling
kspace_crop *= 1e6
masked_kspace, mask = transforms.apply_mask(kspace_crop, self.mask_func, seed)
# zero-filled
zim = transforms.ifft2(masked_kspace)
zim_abs = transforms.complex_abs(zim)
_, mean, std = transforms.normalize_instance(zim_abs, eps=1e-11)
# scaling
target = target * 1e6 #(320,320)
# true edge
gt_edge = torch.from_numpy(Get_sobel(target.numpy())) # 1 channel
gt_edge = gt_edge / gt_edge.max() # normalize
gt_edge = gt_edge * (gt_edge > 0.2)
# zim edge
zim_edge = torch.from_numpy(Get_sobel(zim_abs.numpy()))
# reshape
zim = zim.permute(2,0,1)
zim_edge = zim_edge.unsqueeze(0)
return zim, zim_edge, target, gt_edge, masked_kspace, mask, mean, std, attrs['max'].astype(np.float32), fname, slice
class DataTransform_complex_cc359:
"""
Data Transformer for CC-359
"""
def __init__(self, mask_func, resolution=256, use_seed=True):
"""
Args:
mask_func (common.subsample.MaskFunc): A function that can create a mask of
appropriate shape.
resolution (int): Resolution of the image.
which_challenge (str): Either "singlecoil" or "multicoil" denoting the dataset.
use_seed (bool): If true, this class computes a pseudo random number generator seed
from the filename. This ensures that the same mask is used for all the slices of
a given volume every time.
"""
self.mask_func = mask_func
self.resolution = resolution
self.use_seed = use_seed
def __call__(self, target, maxval, fname, slice):
"""
Args:
target (numpy.array): full-sampled kspace, complex-valued (slice, H, W, 2)
maxval(float): useless, default 0
fname (str): File name
slice (int): Serial number of the slice.
Returns:
(tuple): tuple containing:
image (torch.Tensor): Zero-filled input image.
target (torch.Tensor): Target image converted to a torch Tensor, 1 channel
mean (float): Mean value used for normalization.
std (float): Standard deviation value used for normalization.
norm (float): L2 norm of the entire volume.
"""
seed = None if not self.use_seed else tuple(map(ord, fname))
# full kspace
kspace = transforms.to_tensor(target) #uncentered kspace
kspace = transforms.fftshift(kspace, dim=(-3,-2))
# scaling
kspace /= 1e5
# target
target = transforms.ifftshift(transforms.ifft2(kspace))
target = transforms.complex_abs(target)
# masked kspace
masked_kspace, mask = transforms.apply_mask(kspace, self.mask_func, seed)
# zero-filled
zim = transforms.ifftshift(transforms.ifft2(masked_kspace))
zim_abs = transforms.complex_abs(zim)
_, mean, std = transforms.normalize_instance(zim_abs, eps=1e-11)
zim = zim.permute(2,0,1)
return zim, target, masked_kspace, mask, mean, std, maxval, fname, slice
class DataTransform_complex_cc359_edge:
"""
Data Transformer for CC-359
"""
def __init__(self, mask_func, resolution=256, use_seed=True):
"""
Args:
mask_func (common.subsample.MaskFunc): A function that can create a mask of
appropriate shape.
resolution (int): Resolution of the image.
which_challenge (str): Either "singlecoil" or "multicoil" denoting the dataset.
use_seed (bool): If true, this class computes a pseudo random number generator seed
from the filename. This ensures that the same mask is used for all the slices of
a given volume every time.
"""
self.mask_func = mask_func
self.resolution = resolution
self.use_seed = use_seed
def __call__(self, target, maxval, fname, slice):
"""
Args:
target (numpy.array): full-sampled kspace, complex-valued (slice, H, W, 2)
maxval(float): useless, default 0
fname (str): File name
slice (int): Serial number of the slice.
Returns:
(tuple): tuple containing:
image (torch.Tensor): Zero-filled input image.
target (torch.Tensor): Target image converted to a torch Tensor, 1 channel
mean (float): Mean value used for normalization.
std (float): Standard deviation value used for normalization.
norm (float): L2 norm of the entire volume.
"""
seed = None if not self.use_seed else tuple(map(ord, fname))
# full kspace
kspace = transforms.to_tensor(target) #uncentered kspace
kspace = transforms.fftshift(kspace, dim=(-3,-2))
# scaling
kspace /= 1e5
# target
target = transforms.ifftshift(transforms.ifft2(kspace))
target = transforms.complex_abs(target)
# true edge
gt_edge = torch.from_numpy(Get_sobel(target.numpy())) # 1 channel
gt_edge = gt_edge / gt_edge.max() # normalize
# masked kspace
masked_kspace, mask = transforms.apply_mask(kspace, self.mask_func, seed)
# zero-filled
zim = transforms.ifftshift(transforms.ifft2(masked_kspace))
zim_abs = transforms.complex_abs(zim)
_, mean, std = transforms.normalize_instance(zim_abs, eps=1e-11)
zim = zim.permute(2,0,1) #(2, H, W)
output = {
'zf':zim,
'gt':target,
'subF':masked_kspace,
'mask':mask,
'mean': 0,
'std': 1,
'fname':fname,
'slice_id': slice,
'maxval': 1e5,
'gt_edge':gt_edge,
}
return output
def create_datasets(
dataName,
dataMode,
train_root,
valid_root,
center_fractions,
accelerations,
resolution,
sample_rate,
challenge='singlecoil',
use_sens_map=False,
edge_type='sobel'
):
"""
create dataset, support cardiac(DICOM), fastmri(single/multi coiled) or cc359 dataset(single/multi coiled)
input:
dataName(str): fastmri or cc359
dataMode(str): data type of input data. Real/complex
train_root(str): path of the training data
valid_root(str): path of the validation data
center_fractions(list):
accelerations(list):
resolution(int): 320 for fastmri or 256 for cc359
sample_rate(float):
"""
assert dataName in ['cardiac','fastmri_pd', 'fastmri_pdfs','cc359'], "Only support cardiac/fastmri/cc359 dataset"
if dataName == 'cardiac':
train_data = SliceData_cardiac(train_root, accelerations, isTrain=1)
dev_data = SliceData_cardiac(valid_root, accelerations)
else:
# use fastmri masking function
train_mask = MaskFunc(center_fractions, accelerations)
dev_mask = MaskFunc(center_fractions, accelerations)
# ===========================================
# fastmri
# ===========================================
if 'fastmri' in dataName:
# ===========================================
# singlecoil
# ===========================================
if challenge == 'singlecoil':
if dataMode == 'real':
dt = DataTransform_real_fastmri # for unet
elif dataMode == 'complex':
dt = DataTransform_complex_fastmri
elif dataMode == 'complex_edge':
dt = DataTransform_complex_fastmri_edge
else:
raise NotImplementedError("Only support real/complex/complex_edge dataMode in fastmri dataloader")
# ===========================================
# multicoil
# ===========================================
elif challenge == 'multicoil' and use_sens_map: # special treatment for vsnet
dt = DataTransform_complex_fastmri_multicoil_vsnet
elif challenge == 'multicoil' and not use_sens_map:
dt = DataTransform_complex_fastmri_multicoil
train_data = SliceData_fastmri(
root=train_root,
transform=dt(train_mask, resolution, challenge),
sample_rate=sample_rate,
challenge=challenge,
dataMode=dataMode,
use_sens_map=use_sens_map,
skip_head=1
)
dev_data = SliceData_fastmri(
root=valid_root,
transform=dt(dev_mask, resolution, challenge, use_seed=True),
sample_rate=sample_rate,
challenge=challenge,
dataMode=dataMode,
use_sens_map=use_sens_map,
skip_head=0
)
# ===========================================
# cc359
# ===========================================
elif dataName == 'cc359':
# ===========================================
# singlecoil
# ===========================================
if challenge == 'singlecoil':
if dataMode == 'complex':
dt = DataTransform_complex_cc359
elif dataMode == 'complex_edge':
dt = DataTransform_complex_cc359_edge
else:
raise NotImplementedError("Only support real/complex/complex_edge dataMode in fastmri dataloader")
train_data = SliceData_cc359(
root=train_root,
transform=dt(train_mask),
sample_rate=sample_rate,
)
dev_data = SliceData_cc359(
root=valid_root,
transform=dt(dev_mask, use_seed=True),
sample_rate=sample_rate,
)
# ===========================================
# multicoil
# ===========================================
elif challenge == 'multicoil':
train_data = SliceData_cc359_multicoil(
root=train_root,
crop=(50,50),
center_fractions=center_fractions,
accelerations=accelerations,
shuffle=True,
is_train=True,
dataMode=dataMode,
use_sens_map=use_sens_map,
edge_type=edge_type
)
dev_data = SliceData_cc359_multicoil(
root=valid_root,
crop=(50,50),
center_fractions=center_fractions,
accelerations=accelerations,
shuffle=False,
is_train=False,
dataMode=dataMode,
use_sens_map=use_sens_map,
edge_type=edge_type
)
return dev_data, train_data
def dataFormat(x):
if len(x.shape) == 3:
return x
elif len(x.shape) == 5: #(B, C, H, W, 2)
assert x.shape[-1] == 2, "dataFormat last dimension should be 2"
x = (x**2).sum(dim=-1).sqrt() #(B,-1, H, W)
x = ((x**2).sum(dim=1)).sqrt() #(B,H,W)
elif len(x.shape) == 4:
if x.shape[1] == 1: #(B,1,H,W)
x = x.squeeze(1)
elif x.shape[1] == 2: #single coil (B,2,H,W)
x = (x**2).sum(dim=1).sqrt()
else: #(B,C,H,W)
assert len(x.shape) == 4, "dataFormat do not support dynamic MRI"
B, C, H, W = x.shape
x = x.reshape(B,-1,H,W,2)
x = (x**2).sum(dim=-1).sqrt() #(B,-1, H, W)
x = ((x**2).sum(dim=1)).sqrt() #(B,H,W)
return x
def getDataloader(
dataName,
dataMode,
batch_size,
center_fractions,
accelerations,
resolution,
train_root,
valid_root,
sample_rate=1,
challenge='singlecoil',
use_sens_map=False,
edge_type='sobel'
):
# create slice dataset
dev_data, train_data = create_datasets(dataName, dataMode, train_root, valid_root, center_fractions, accelerations, resolution, sample_rate, challenge, use_sens_map, edge_type)