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: if not os.path.isdir(args.img_dir): raise ValueError( '(-i / --img-dir) argument needs to be a directory of NIfTI images.' ) if args.mask_dir is not None: if not os.path.isdir(args.mask_dir): raise ValueError( '(-m / --mask-dir) argument needs to be a directory of NIfTI images.' ) ax = all_hists(args.img_dir, args.mask_dir, alpha=args.alpha, figsize=args.figsize, lw=args.linewidth) if args.plot_title is not None: ax.set_title(args.plot_title) plt.savefig(args.out_name) return 0 except Exception as e: logger.exception(e) return 1
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: if not os.path.isdir(args.img_dir): raise ValueError('(-i / --img-dir) argument needs to be a directory of NIfTI images.') if args.mask_dir is not None: if not os.path.isdir(args.mask_dir): raise ValueError('(-m / --mask-dir) argument needs to be a directory of NIfTI images.') _ = lsq.lsq_normalize(args.img_dir, args.mask_dir, args.output_dir) 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(args.output_dir, args.mask_dir) ax.set_title('Least Squares') plt.savefig(os.path.join(args.output_dir, 'hist.png')) return 0 except Exception as e: logger.exception(e) return 1
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: ax = all_hists(args.img_dir, args.mask_dir, alpha=args.alpha, figsize=args.figsize, lw=args.linewidth) if args.plot_title is not None: ax.set_title(args.plot_title) plt.savefig(args.out_name) return 0 except Exception as e: logger.exception(e) return 1
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: _ = hm.hm_normalize(args.img_dir, args.mask_dir, args.output_dir) 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(args.output_dir, args.mask_dir) ax.set_title('Histogram Matching') plt.savefig(os.path.join(args.output_dir, 'hist.png')) return 0 except Exception as e: logger.exception(e) return 1
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: if not args.single_img: if not os.path.isdir(args.image) or not os.path.isdir( args.brain_mask): raise NormalizationError( 'if single-img option off, then image and brain-mask must be directories' ) img_fns = io.glob_nii(args.image) mask_fns = io.glob_nii(args.brain_mask) if len(img_fns) != len(mask_fns) and len(img_fns) > 0: raise NormalizationError( 'input images and masks must be in correspondence and greater than zero ' '({:d} != {:d})'.format(len(img_fns), len(mask_fns))) for i, (img, mask) in enumerate(zip(img_fns, mask_fns), 1): _, base, _ = io.split_filename(img) logger.info('Normalizing image {} ({:d}/{:d})'.format( img, i, len(img_fns))) process(img, mask, args, logger) else: if not os.path.isfile(args.image) or not os.path.isfile( args.brain_mask): raise NormalizationError( 'if single-img option on, then image and brain-mask must be files' ) process(args.image, args.brain_mask, args, logger) 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(args.output_dir, args.brain_mask) ax.set_title('GMM') plt.savefig(os.path.join(args.output_dir, 'hist.png')) return 0 except Exception as e: logger.exception(e) return 1
def main(args=None): args = arg_parser().parse_args(args) if not (args.brain_mask is None) ^ (args.tissue_mask is None): raise NormalizationError( 'Only one of {brain mask, tissue mask} should be given') 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: if not args.single_img: if not os.path.isdir( args.image) or (False if args.brain_mask is None else not os.path.isdir(args.brain_mask)): raise NormalizationError( 'if single-img option off, then image and brain-mask must be directories' ) img_fns = io.glob_nii(args.image) mask_fns = io.glob_nii( args.brain_mask ) if args.brain_mask is not None else [None] * len(img_fns) if len(img_fns) != len(mask_fns) and len(img_fns) > 0: raise NormalizationError( 'input images and masks must be in correspondence and greater than zero ' '({:d} != {:d})'.format(len(img_fns), len(mask_fns))) args.output_dir = args.output_dir or 'fcm' output_dir_base = os.path.abspath( os.path.join(args.output_dir, '..')) if args.contrast.lower() == 't1' and args.tissue_mask is None: tissue_mask_dir = os.path.join(output_dir_base, 'tissue_masks') if os.path.exists(tissue_mask_dir): logger.warning( 'Tissue mask directory already exists, may overwrite existing tissue masks!' ) else: logger.info('Creating tissue mask directory: {}'.format( tissue_mask_dir)) os.mkdir(tissue_mask_dir) for i, (img, mask) in enumerate(zip(img_fns, mask_fns), 1): _, base, _ = io.split_filename(img) _, mask_base, _ = io.split_filename(mask) logger.info( 'Creating tissue mask for {} ({:d}/{:d})'.format( base, i, len(img_fns))) logger.debug('Tissue mask {} ({:d}/{:d})'.format( mask_base, i, len(img_fns))) process(img, mask, None, tissue_mask_dir, args, logger) elif os.path.exists(args.tissue_mask): tissue_mask_dir = args.tissue_mask else: raise NormalizationError( 'If contrast is not t1, then tissue mask directory ({}) ' 'must already be created!'.format(args.tissue_mask)) tissue_masks = io.glob_nii(tissue_mask_dir) for i, (img, tissue_mask) in enumerate(zip(img_fns, tissue_masks), 1): dirname, base, _ = io.split_filename(img) _, tissue_base, _ = io.split_filename(tissue_mask) logger.info('Normalizing image {} ({:d}/{:d})'.format( base, i, len(img_fns))) logger.debug('Tissue mask {} ({:d}/{:d})'.format( tissue_base, i, len(img_fns))) if args.output_dir is not None: dirname = args.output_dir process(img, None, tissue_mask, dirname, args, logger) else: if not os.path.isfile(args.image): raise NormalizationError( 'if single-img option on, then image must be a file') if args.tissue_mask is None and args.contrast.lower() == 't1': logger.info('Creating tissue mask for {}'.format(args.image)) process(args.image, args.brain_mask, None, args.output_dir, args, logger) elif os.path.isfile(args.tissue_mask): pass else: raise NormalizationError( 'If contrast is not t1, then tissue mask must be provided!' ) logger.info('Normalizing image {}'.format(args.image)) dirname, base, _ = io.split_filename(args.image) dirname = args.output_dir or dirname if args.tissue_mask is None: tissue_mask = os.path.join( dirname, base + '_{}_mask.nii.gz'.format(args.tissue_type)) else: tissue_mask = args.tissue_mask process(args.image, args.brain_mask, tissue_mask, dirname, args, logger) 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(args.output_dir, args.brain_mask) ax.set_title('Fuzzy C-Means') plt.savefig(os.path.join(args.output_dir, 'hist.png')) return 0 except Exception as e: logger.exception(e) return 1
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 test_all_hist(self): from intensity_normalization.plot.hist import all_hists _ = all_hists(self.data_dir, self.mask_dir)
def test_all_hist(self): _ = all_hists(self.data_dir, self.mask_dir)