def test_ravel_normalization_csf_masks(self): from intensity_normalization.normalize.ravel import ravel_normalize normalized = ravel_normalize(self.data_dir, self.mask_dir, 'T1', write_to_disk=False, csf_masks=True)
def main(args=None): args = arg_parser().parse_args(args) if args.verbosity == 1: level = logging.getLevelName('INFO') elif args.verbosity >= 2: level = logging.getLevelName('DEBUG') else: level = logging.getLevelName('WARNING') logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=level) logger = logging.getLogger(__name__) try: img_fns = io.glob_nii(args.img_dir) mask_fns = io.glob_nii(args.mask_dir) if len(img_fns) != len(mask_fns) or len(img_fns) == 0: raise NormalizationError( 'Image directory ({}) and mask directory ({}) must contain the same ' '(positive) number of images!'.format(args.img_dir, args.mask_dir)) logger.info('Normalizing the images according to RAVEL') Z, _ = ravel.ravel_normalize( args.img_dir, args.mask_dir, args.contrast, do_whitestripe=args.no_whitestripe, b=args.num_unwanted_factors, membership_thresh=args.control_membership_threshold, do_registration=args.no_registration, segmentation_smoothness=args.segmentation_smoothness, use_fcm=not args.use_atropos, sparse_svd=args.sparse_svd, csf_masks=args.csf_masks) V = ravel.image_matrix(img_fns, args.contrast, masks=mask_fns) V_norm = ravel.ravel_correction(V, Z) normalized = ravel.image_matrix_to_images(V_norm, img_fns) # save the normalized images to disk output_dir = os.getcwd( ) if args.output_dir is None else args.output_dir out_fns = [] for fn in img_fns: _, base, ext = io.split_filename(fn) out_fns.append(os.path.join(output_dir, base + '_ravel' + ext)) if not os.path.exists(output_dir): os.mkdir(output_dir) for norm, out_fn in zip(normalized, out_fns): norm.to_filename(out_fn) if args.plot_hist: with warnings.catch_warnings(): warnings.filterwarnings('ignore', category=FutureWarning) from intensity_normalization.plot.hist import all_hists import matplotlib.pyplot as plt ax = all_hists(output_dir, args.mask_dir) ax.set_title('RAVEL') plt.savefig(os.path.join(output_dir, 'hist.png')) return 0 except Exception as e: logger.exception(e) return 1
def run_intensity_ravel(outfolder): from intensity_normalization.normalize import ravel from intensity_normalization.utilities import io, csf try: images = [] brainMasks = [] csfMasks = [] _, _, filenames = next(walk(outfolder)) for f in filenames: filename = f.split(sep)[-1].split(".")[0] images.append(io.open_nii(join(outfolder, f.split(sep)[-1]))) brainMasks.append( io.open_nii( join(outfolder, 'robex_masks', filename + "_mask.nii.gz"))) if not exists(join(outfolder, "Robex")): makedirs(join(outfolder, "Robex")) if not exists(join(outfolder, "csf_masks")): makedirs(join(outfolder, "csf_masks")) print("creating csf masks...") for image, brainMask, f in zip(images, brainMasks, filenames): filename = f.split(sep)[-1].split(".")[0] csfMask = csf.csf_mask(image, brainMask, contrast='T1', csf_thresh=0.9, return_prob=False, mrf=0.25, use_fcm=False) output = nib.Nifti1Image(csfMask, None) io.save_nii( output, join(outfolder, 'csf_masks', filename + "_csfmask.nii.gz")) shutil.move(join(outfolder, f.split(sep)[-1]), join(outfolder, "Robex")) print('running intensity ravel...') ravel.ravel_normalize(join(outfolder, 'Robex'), join(outfolder, 'csf_masks'), 'T1', output_dir=outfolder, write_to_disk=True, do_whitestripe=True, b=1, membership_thresh=0.99, segmentation_smoothness=0.25, do_registration=False, use_fcm=True, sparse_svd=False, csf_masks=True) for i in filenames: rename( join(outfolder, i.split(sep)[-1]), join(outfolder, i.split(sep)[-1].split(".")[0] + "_RAVEL.nii.gz")) except: e = sys.exc_info() print("Error: ", str(e[0])) print("Error: ", str(e[1])) print("Error: executing ravel method") sys.exit(2)