@@ -383,8 +383,10 @@ def _run_interface(self, runtime):
383383class HarmonizeInputSpec (BaseInterfaceInputSpec ):
384384 in_file = File (exists = True , mandatory = True , desc = 'input data (after bias correction)' )
385385 wm_mask = File (exists = True , mandatory = True , desc = 'white-matter mask' )
386+ brain_mask = File (exists = True , desc = 'brain mask (fall-back in case [near]-empty WM mask)' )
386387 erodemsk = traits .Bool (True , usedefault = True , desc = 'erode mask' )
387388 thresh = traits .Float (0.9 , usedefault = True , desc = 'WM probability threshold' )
389+ min_size = traits .Int (30 , usedefault = True , desc = 'minimum number of voxels in binary WM mask' )
388390
389391
390392class HarmonizeOutputSpec (TraitedSpec ):
@@ -401,19 +403,26 @@ class Harmonize(SimpleInterface):
401403
402404 def _run_interface (self , runtime ):
403405 in_file = nb .load (self .inputs .in_file )
406+ data = in_file .get_fdata ()
407+
404408 wm_mask = nb .load (self .inputs .wm_mask ).get_fdata ()
405- wm_mask [wm_mask < 0.9 ] = 0
409+ wm_mask [wm_mask < self . inputs . thresh ] = 0
406410 wm_mask [wm_mask > 0 ] = 1
407- wm_mask = wm_mask .astype (np .uint8 )
408-
409- if self .inputs .erodemsk :
411+ wm_mask = wm_mask .astype (bool )
412+ wm_mask_size = wm_mask .sum ()
413+
414+ if wm_mask_size < self .inputs .min_size :
415+ brain_mask = nb .load (self .inputs .brain_mask ).get_fdata () > 0.5
416+ wm_mask = brain_mask .copy ()
417+ wm_mask [data < np .percentile (data [brain_mask ], 75 )] = False
418+ wm_mask [data > np .percentile (data [brain_mask ], 95 )] = False
419+ elif self .inputs .erodemsk :
410420 # Create a structural element to be used in an opening operation.
411421 struct = nd .generate_binary_structure (3 , 2 )
412422 # Perform an opening operation on the background data.
413- wm_mask = nd .binary_erosion (wm_mask , structure = struct ).astype (np . uint8 )
423+ wm_mask = nd .binary_erosion (wm_mask . astype ( np . uint8 ) , structure = struct ).astype (bool )
414424
415- data = in_file .get_fdata ()
416- data *= 1000.0 / np .median (data [wm_mask > 0 ])
425+ data *= 1000.0 / np .median (data [wm_mask ])
417426
418427 out_file = fname_presuffix (self .inputs .in_file , suffix = '_harmonized' , newpath = '.' )
419428 in_file .__class__ (data , in_file .affine , in_file .header ).to_filename (out_file )
0 commit comments