def main(): parser = _build_arg_parser() args = parser.parse_args() tracts_path = args.tracts assert_inputs_exist(parser, [tracts_path, args.fodf]) assert_outputs_exists(parser, args, [args.afd_mean_map, args.rd_mean_map]) check_tracts_support(parser, tracts_path, args.tracts_producer) streamlines = load_tracts_over_grid( tracts_path, args.fodf, start_at_corner=True, tract_producer=args.tracts_producer) fodf_img = nb.load(args.fodf) afd_mean_map, rd_mean_map = afd_map_along_streamlines( streamlines, fodf_img.get_data(), args.fodf_basis, args.jump) nb.Nifti1Image(afd_mean_map.astype('float32'), fodf_img.get_affine()).to_filename(args.afd_mean_map) nb.Nifti1Image(rd_mean_map.astype('float32'), fodf_img.get_affine()).to_filename(args.rd_mean_map)
def main(): parser = _build_arg_parser() args = parser.parse_args() assert_inputs_exist(parser, [args.bundle]) assert_outputs_exists(parser, args, [args.pruned_bundle]) if args.min_length < 0: parser.error('--min_length {} should be at least 0'.format( args.min_length)) if args.max_length <= args.min_length: parser.error( '--max_length {} should be greater than --min_length'.format( args.max_length)) tractogram = nib.streamlines.load(args.bundle) streamlines = tractogram.streamlines pruned_streamlines = subsample_streamlines(streamlines, args.min_length, args.max_length) if not pruned_streamlines: print("Pruning removed all the streamlines. Please adjust " "--{min,max}_length") else: pruned_tractogram = Tractogram(pruned_streamlines, affine_to_rasmm=np.eye(4)) nib.streamlines.save(pruned_tractogram, args.pruned_bundle, header=tractogram.header)
def main(): parser = _build_arg_parser() args = parser.parse_args() assert_inputs_exist(parser, args.input) assert_outputs_exists(parser, args, [args.output]) # Load reference image first_path = args.input[0] img_ref = nib.load(first_path) img_ref_datatype = img_ref.get_data_dtype() img_ref_shape = img_ref.get_header().get_data_shape() # Create output array out_data = np.zeros(img_ref_shape, dtype=img_ref_datatype) for input_im in args.input: in_im = nib.load(input_im) if in_im.get_data_dtype() != img_ref_datatype: raise TypeError(("Datatype of image: {} does not match datatype " "of image: {}").format(input_im, first_path)) if in_im.get_header().get_data_shape() != img_ref_shape: raise TypeError(("Shape of image: {} does not match shape of " "image: {}").format(input_im, first_path)) out_data += in_im.get_data() img_out = nib.Nifti1Image(out_data, img_ref.get_affine()) nib.save(img_out, args.output)
def main(): parser = _build_arg_parser() args = parser.parse_args() assert_inputs_exist(parser, [args.bundle, args.reference]) assert_outputs_exists(parser, args, [args.endpoints_map]) bundle_tractogram_file = nib.streamlines.load(args.bundle) if int(bundle_tractogram_file.header['nb_streamlines']) == 0: logging.warning('Empty bundle file {}. Skipping'.format(args.bundle)) return reference = nib.load(args.reference) bundle_streamlines_vox = load_in_voxel_space(bundle_tractogram_file, reference) endpoints_map = np.zeros(reference.shape) for streamline in bundle_streamlines_vox: xyz = streamline[0, :].astype(int) endpoints_map[xyz[0], xyz[1], xyz[2]] += 1 xyz = streamline[-1, :].astype(int) endpoints_map[xyz[0], xyz[1], xyz[2]] += 1 nib.save( nib.Nifti1Image(endpoints_map, reference.affine, reference.header), args.endpoints_map) bundle_name, _ = os.path.splitext(os.path.basename(args.bundle)) stats = {bundle_name: {'count': np.count_nonzero(endpoints_map)}} print(json.dumps(stats, indent=args.indent))
def main(): parser = build_args_parser() args = parser.parse_args() assert_inputs_exist(parser, [args.image]) assert_outputs_exists(parser, args, [args.reordered_image_path]) indices = [str_to_index(axis) for axis in list(args.axes)] if len(indices) != 3 or {0, 1, 2} != set(indices): parser.error('The axes parameter must contain x, y and z in whatever ' 'order.') img = nib.load(args.image) data = img.get_data() swaps = [axis for index, axis in enumerate(indices) if index != axis] for i in range(len(swaps) - 1): data = np.swapaxes(data, swaps[i], swaps[i + 1]) new_zooms = np.array(img.get_header().get_zooms())[list(indices)] if len(data.shape) == 4: new_zooms = np.append(new_zooms, 1.0) img.get_header().set_zooms(new_zooms) nib.Nifti1Image(data, img.get_affine(), img.get_header()). \ to_filename(args.reordered_image_path)
def main(): parser = _build_args_parser() args = parser.parse_args() assert_inputs_exist(parser, [args.in_tractogram]) assert_outputs_exists(parser, args, args.out_tractogram) tractogram_file = load(args.in_tractogram) streamlines = list(tractogram_file.streamlines) data_per_point = tractogram_file.tractogram.data_per_point data_per_streamline = tractogram_file.tractogram.data_per_streamline new_streamlines, new_per_point, new_per_streamline = get_subset_streamlines( streamlines, data_per_point, data_per_streamline, args.max_num_streamlines, args.seed) new_tractogram = Tractogram(new_streamlines, data_per_point=new_per_point, data_per_streamline=new_per_streamline, affine_to_rasmm=np.eye(4)) save(new_tractogram, args.out_tractogram, header=tractogram_file.header)
def main(): parser = _build_arg_parser() args = parser.parse_args() assert_inputs_exist(parser, [args.input, args.fa, args.md]) assert_outputs_exists(parser, args, [], [args.max_value_output, args.mask_output]) if args.verbose: logging.basicConfig(level=logging.DEBUG) # Load input image fodf, affine, zoom = load(args.input) fa, _, _ = load(args.fa) md, _, _ = load(args.md) value, mask = get_ventricles_max_fodf(fodf, fa, md, zoom, args) if args.mask_output: save(mask, affine, args.mask_output) if args.max_value_output: text_file = open(args.max_value_output, "w") text_file.write(str(value)) text_file.close() else: print("Maximal value in ventricles: {}".format(value))
def main(): parser = _build_args_parser() args = parser.parse_args() assert_inputs_exist(parser, [args.tracts, args.ref_anat]) assert_outputs_exists(parser, args, [args.out]) check_tracts_support(parser, args.tracts, args.tracts_producer) max_ = np.iinfo(np.int16).max if args.binary is not None and (args.binary <= 0 or args.binary > max_): parser.error( 'The value of --binary ({}) ' 'must be greater than 0 and smaller or equal to {}'.format( args.binary, max_)) streamlines = list( load_tracts_over_grid(args.tracts, args.ref_anat, start_at_corner=True, tract_producer=args.tracts_producer)) # Compute weighting matrix taking the compression into account ref_img = nb.load(args.ref_anat) anat_dim = ref_img.get_header().get_data_shape() tract_counts = compute_robust_tract_counts_map(streamlines, anat_dim) if args.binary is not None: tract_counts[tract_counts > 0] = args.binary bin_img = nb.Nifti1Image(tract_counts.astype(np.int16), ref_img.get_affine()) nb.save(bin_img, args.out)
def main(): parser = _build_arg_parser() args = parser.parse_args() matplotlib.style.use('ggplot') assert_inputs_exist(parser, [args.input, args.mask]) assert_outputs_exists(parser, args, [args.output]) in_data = nib.load(args.input).get_data() mask_data = nib.load(args.mask).get_data() if in_data.shape[:3] != mask_data.shape[:3]: raise Exception( '[X, Y, Z] shape of input and mask image needs to be the same. ' '{} != {}'.format(in_data.shape[:3], mask_data.shape[:3])) fig = plt.figure() fig.set_size_inches(640.0 / fig.get_dpi(), 480.0 / fig.get_dpi()) nz_in_data = in_data[np.nonzero(mask_data)] mu = np.mean(nz_in_data) sigma = np.std(nz_in_data) plt.title(r'$\mu={}$, $\sigma={}$'.format(mu, sigma)) plt.hist(nz_in_data) if args.label: fig.suptitle(args.label) fig.savefig(args.output, dpi=fig.get_dpi()) plt.close(fig)
def main(): parser = _build_arg_parser() args = parser.parse_args() assert_inputs_exist(parser, [args.input]) assert_outputs_exists(parser, args, args.output) if not args.output.endswith('.trk'): parser.error('Output file needs to end with .trk') if len(args.color) != 8: parser.error('Hexadecimal RGB color should be formatted as 0xRRGGBB') color_int = int(args.color, 0) red = color_int >> 16 green = (color_int & 0x00FF00) >> 8 blue = color_int & 0x0000FF tractogram_file = nib.streamlines.load(args.input) tractogram_file.tractogram.data_per_point["color"] = [ np.tile([red, green, blue], (len(i), 1)) for i in tractogram_file.streamlines ] nib.streamlines.save(tractogram_file.tractogram, args.output, header=tractogram_file.header)
def main(): parser = _build_args_parser() args = parser.parse_args() assert_inputs_exist(parser, [args.input_path], [args.input_bbox]) assert_outputs_exists(parser, args, [args.output_path], [args.output_bbox]) img = nib.load(args.input_path) if args.input_bbox: with open(args.input_bbox, 'r') as bbox_file: wbbox = pickle.load(bbox_file) if not args.ignore_voxel_size: voxel_size = img.header.get_zooms()[0:3] if not np.allclose(voxel_size, wbbox.voxel_size): raise IOError("Bounding box and data voxel sizes are not " "compatible. Use option --ignore_voxel_size " "to ignore this test.") else: wbbox = compute_nifti_bounding_box(img) if args.output_bbox: with open(args.output_bbox, 'w') as bbox_file: pickle.dump(wbbox, bbox_file) out_nifti_file = crop_nifti(img, wbbox) nib.save(out_nifti_file, args.output_path)
def main(): parser = _build_arg_parser() args = parser.parse_args() assert_inputs_exist(parser, [args.input_sh]) assert_outputs_exists(parser, args, [args.output_name]) input_basis = args.sh_basis output_basis = 'descoteaux07' if input_basis == 'tournier07' else 'tournier07' sph_harm_basis_ori = sph_harm_lookup.get(input_basis) sph_harm_basis_des = sph_harm_lookup.get(output_basis) sphere = get_sphere('repulsion724').subdivide(1) img = nib.load(args.input_sh) data = img.get_data() sh_order = find_order_from_nb_coeff(data) b_ori, m_ori, n_ori = sph_harm_basis_ori(sh_order, sphere.theta, sphere.phi) b_des, m_des, n_des = sph_harm_basis_des(sh_order, sphere.theta, sphere.phi) l_des = -n_des * (n_des + 1) inv_b_des = smooth_pinv(b_des, 0 * l_des) indices = np.argwhere(np.any(data, axis=3)) for i, ind in enumerate(indices): ind = tuple(ind) sf_1 = np.dot(data[ind], b_ori.T) data[ind] = np.dot(sf_1, inv_b_des.T) img = nib.Nifti1Image(data, img.affine, img.header) nib.save(nib.Nifti1Image(data, img.affine, img.header), args.output_name)
def main(): parser = _build_arg_parser() args = parser.parse_args() assert_inputs_exist( parser, [args.map_include, args.map_exclude, args.additional_mask]) assert_outputs_exists(parser, args, [args.map_include_corr, args.map_exclude_corr]) map_inc = nib.load(args.map_include) map_inc_data = map_inc.get_data() map_exc = nib.load(args.map_exclude) map_exc_data = map_exc.get_data() additional_mask = nib.load(args.additional_mask) additional_mask_data = additional_mask.get_data() map_inc_data[additional_mask_data > 0] = 0 map_exc_data[additional_mask_data > 0] = 0 nib.save( nib.Nifti1Image(map_inc_data.astype('float32'), map_inc.affine, map_inc.header), args.map_include_corr) nib.save( nib.Nifti1Image(map_exc_data.astype('float32'), map_exc.affine, map_exc.header), args.map_exclude_corr)
def main(): parser = build_args_parser() args = parser.parse_args() if args.verbose: logging.basicConfig(level=logging.INFO) img_inputs = [s for s in args.inputs if s != 'ones'] if len(img_inputs): assert_inputs_exist(parser, img_inputs) assert_outputs_exists(parser, args, [args.output]) # Load all input masks. masks = [load_data(f) for f in args.inputs] # Apply the requested operation to each input file. logging.info('Performing operation \'{}\'.'.format(args.operation)) mask = reduce(OPERATIONS[args.operation], masks) if args.threshold: mask = (mask > args.threshold).astype(np.uint8) affine = next( nibabel.load(f).affine for f in args.inputs if os.path.isfile(f)) new_img = nibabel.Nifti1Image(mask, affine) nibabel.save(new_img, args.output)
def main(): parser = _build_args_parser() args = parser.parse_args() assert_inputs_exist(parser, [args.input]) assert_outputs_exists(parser, args, [args.output], [args.logfile, args.save_piesno_mask]) logging.basicConfig() log = logging.getLogger(__name__) if args.verbose: log.setLevel(level=logging.INFO) else: log.setLevel(level=logging.WARNING) if args.logfile is not None: log.addHandler(logging.FileHandler(args.logfile, mode='w')) vol = nib.load(args.input) data = vol.get_data() if args.mask is None: mask = np.ones(data.shape[:3], dtype=np.bool) else: mask = nib.load(args.mask).get_data().astype(np.bool) sigma = args.sigma noise_method = args.noise_method if args.N == 0 and sigma is None and noise_method == PIESNO: raise ValueError('PIESNO is not designed for Gaussian noise, but you ' 'specified N = 0.') # Check if dataset is 3D. If so, ensure the user didn't ask for PIESNO. # This is unsupported. if data.ndim == 3 and noise_method == PIESNO: parser.error('Cannot use PIESNO noise estimation with a 3D dataset. ' 'Please use the basic estimation') if sigma is not None: log.info('User supplied noise standard deviation is %s', sigma) # Broadcast the single value to a whole 3D volume for nlmeans sigma = np.ones(data.shape[:3]) * sigma else: log.info('Estimating noise with method %s', args.noise_method) if args.noise_method == PIESNO: sigma = _get_piesno_sigma(vol, log, args) else: sigma = _get_basic_sigma(vol.get_data(), log) with warnings.catch_warnings(): warnings.simplefilter("ignore", category=DeprecationWarning) data_denoised = nlmeans(data, sigma, mask=mask, rician=args.N > 0, num_threads=args.nbr_processes) nib.save(nib.Nifti1Image(data_denoised, vol.affine, vol.header), args.output)
def main(): parser = _build_arg_parser() args = parser.parse_args() if not args.not_all: args.afd = args.afd or 'afd_max.nii.gz' args.afd_total = args.afd_total or 'afd_total_sh0.nii.gz' args.afd_sum = args.afd_sum or 'afd_sum.nii.gz' args.nufo = args.nufo or 'nufo.nii.gz' args.peaks = args.peaks or 'peaks.nii.gz' arglist = [args.afd, args.afd_total, args.afd_sum, args.nufo, args.peaks] if args.not_all and not any(arglist): parser.error('When using --not_all, you need to specify at least ' 'one file to output.') assert_inputs_exist(parser, []) assert_outputs_exists(parser, args, arglist) data, affine = load(args.input) if args.mask is None: mask = np.ones(data.shape[:-1]) else: mask, affine2 = load(args.mask) nufo_map, afd_map, afd_sum, peaks_dirs = get_maps(data, mask, args) # Save result if args.nufo: save(nufo_map, affine, args.nufo) if args.afd: save(afd_map, affine, args.afd) if args.afd_total: # this is the analytical afd total afd_tot = data[:, :, :, 0] save(afd_tot, affine, args.afd_total) if args.afd_sum: save(afd_sum, affine, args.afd_sum) if args.peaks: nib.save( nib.Nifti1Image(reshape_peaks_for_visualization(peaks_dirs), affine), args.peaks) if args.visu: if nufo_map.max() > nufo_map.min(): nufo_map = (255 * (nufo_map - nufo_map.min()) / (nufo_map.max() - nufo_map.min())) if afd_map.max() > afd_map.min(): afd_map = (255 * (afd_map - afd_map.min()) / (afd_map.max() - afd_map.min())) save(nufo_map, affine, args.nufo, True) save(afd_map, affine, args.afd, True)
def main(): parser = _build_arg_parser() args = parser.parse_args() output_names = [ 'axial_superior', 'axial_inferior', 'coronal_posterior', 'coronal_anterior', 'sagittal_left', 'sagittal_right' ] output_paths = [ os.path.join(os.path.dirname(args.output), '{}_' + os.path.basename(args.output)).format(name) for name in output_names ] assert_inputs_exist(parser, [args.bundle, args.map]) assert_outputs_exists(parser, args, output_paths) assignment = np.load(args.map)['arr_0'] lut = actor.colormap_lookup_table(scale_range=(np.min(assignment), np.max(assignment)), hue_range=(0.1, 1.), saturation_range=(1, 1.), value_range=(1., 1.)) tubes = actor.line(nib.streamlines.load(args.bundle).streamlines, assignment, lookup_colormap=lut) scalar_bar = actor.scalar_bar(lut) ren = window.Renderer() ren.add(tubes) ren.add(scalar_bar) window.snapshot(ren, output_paths[0]) ren.pitch(180) ren.reset_camera() window.snapshot(ren, output_paths[1]) ren.pitch(90) ren.set_camera(view_up=(0, 0, 1)) ren.reset_camera() window.snapshot(ren, output_paths[2]) ren.pitch(180) ren.set_camera(view_up=(0, 0, 1)) ren.reset_camera() window.snapshot(ren, output_paths[3]) ren.yaw(90) ren.reset_camera() window.snapshot(ren, output_paths[4]) ren.yaw(180) ren.reset_camera() window.snapshot(ren, output_paths[5])
def main(): parser = _build_args_parser() args = parser.parse_args() assert_inputs_exist(parser, [args.input], [args.ref]) assert_outputs_exists(parser, args, [args.output]) if args.enforce_dimensions and not args.ref: parser.error("Cannot enforce dimensions without a reference image") if args.verbose: logging.basicConfig(level=logging.DEBUG) logging.debug('Loading Raw data from %s', args.input) img = nib.load(args.input) data = img.get_data() affine = img.get_affine() original_zooms = img.get_header().get_zooms()[:3] if args.ref: ref_img = nib.load(args.ref) new_zooms = ref_img.header.get_zooms()[:3] elif args.resolution: new_zooms = [args.resolution] * 3 elif args.iso_min: min_zoom = min(original_zooms) new_zooms = (min_zoom, min_zoom, min_zoom) logging.debug('Data shape: %s', data.shape) logging.debug('Data affine: %s', affine) logging.debug('Data affine setup: %s', nib.aff2axcodes(affine)) logging.debug('Resampling data to %s with mode %s', new_zooms, args.interp) data2, affine2 = reslice(data, affine, original_zooms, new_zooms, interp_code_to_order(args.interp)) logging.debug('Resampled data shape: %s', data2.shape) logging.debug('Resampled data affine: %s', affine2) logging.debug('Resampled data affine setup: %s', nib.aff2axcodes(affine2)) logging.debug('Saving resampled data to %s', args.output) if args.enforce_dimensions: computed_dims = data2.shape ref_dims = ref_img.shape[:3] if computed_dims != ref_dims: fix_dim_volume = np.zeros(ref_dims) x_dim = min(computed_dims[0], ref_dims[0]) y_dim = min(computed_dims[1], ref_dims[1]) z_dim = min(computed_dims[2], ref_dims[2]) fix_dim_volume[:x_dim, :y_dim, :z_dim] = \ data2[:x_dim, :y_dim, :z_dim] data2 = fix_dim_volume nib.save(nib.Nifti1Image(data2, affine2), args.output)
def main(): parser = _build_arg_parser() args = parser.parse_args() assert_inputs_exist( parser, [args.bundle, args.centroid_streamline, args.reference]) assert_outputs_exists(parser, args, [args.output_map]) bundle_tractogram_file = nib.streamlines.load(args.bundle) centroid_tractogram_file = nib.streamlines.load(args.centroid_streamline) if int(bundle_tractogram_file.header['nb_streamlines']) == 0: logger.warning('Empty bundle file {}. Skipping'.format(args.bundle)) return if int(centroid_tractogram_file.header['nb_streamlines']) != 1: logger.warning('Centroid file {} should contain one streamline. ' 'Skipping'.format(args.centroid_streamline)) return ref_img = nib.load(args.reference) bundle_streamlines_vox = load_in_voxel_space(bundle_tractogram_file, ref_img) bundle_streamlines_vox._data *= args.upsample number_of_centroid_points = len(centroid_tractogram_file.streamlines[0]) if number_of_centroid_points > 99: raise Exception('Invalid number of points in the centroid. You should ' 'have a maximum of 99 points in your centroid ' 'streamline. ' 'Current is {}'.format(number_of_centroid_points)) centroid_streamlines_vox = load_in_voxel_space(centroid_tractogram_file, ref_img) centroid_streamlines_vox._data *= args.upsample upsampled_shape = [s * args.upsample for s in ref_img.shape] tdi_mask = compute_robust_tract_counts_map(bundle_streamlines_vox, upsampled_shape) > 0 tdi_mask_nzr = np.nonzero(tdi_mask) tdi_mask_nzr_ind = np.transpose(tdi_mask_nzr) min_dist_ind, _ = min_dist_to_centroid(tdi_mask_nzr_ind, centroid_streamlines_vox[0]) # Save the (upscaled) labels mask labels_mask = np.zeros(tdi_mask.shape) labels_mask[tdi_mask_nzr] = min_dist_ind + 1 # 0 is background value rescaled_affine = ref_img.affine rescaled_affine[:3, :3] /= args.upsample labels_img = nib.Nifti1Image(labels_mask, rescaled_affine) upsampled_spacing = ref_img.header['pixdim'][1:4] / args.upsample labels_img.header.set_zooms(upsampled_spacing) nib.save(labels_img, args.output_map)
def main(): parser = build_args_parser() args = parser.parse_args() if args.verbose: logging.basicConfig(level=logging.INFO) assert_inputs_exist(parser, [args.dwi, args.bvals, args.bvecs]) assert_outputs_exists( parser, args, [args.output_dwi, args.output_bvals, args.output_bvecs]) bvals, bvecs = read_bvals_bvecs(args.bvals, args.bvecs) # Find the volume indices that correspond to the shells to extract. tol = args.tolerance indices = [ get_shell_indices(bvals, shell, tol=tol) for shell in args.bvals_to_extract ] indices = np.unique(np.sort(np.hstack(indices))) if len(indices) == 0: parser.error('There are no volumes that have the supplied b-values.') logging.info( 'Extracting shells [{}], with number of images per shell [{}], ' 'from {} images from {}.'.format( ' '.join([str(b) for b in args.bvals_to_extract]), ' '.join([ str(len(get_shell_indices(bvals, shell))) for shell in args.bvals_to_extract ]), len(bvals), args.dwi)) img = nib.load(args.dwi) if args.block_size is None: args.block_size = img.shape[-1] # Load the shells by iterating through blocks of volumes. This approach # is slower for small files, but allows very big files to be split # with less memory usage. shell_data = np.zeros((img.shape[:-1] + (len(indices), ))) for vi, data in volumes(img, args.block_size): in_volume = np.array([i in vi for i in indices]) in_data = np.array([i in indices for i in vi]) shell_data[..., in_volume] = data[..., in_data] bvals = bvals[indices].astype(int) bvals.shape = (1, len(bvals)) np.savetxt(args.output_bvals, bvals, '%d') np.savetxt(args.output_bvecs, bvecs[indices, :].T, '%0.15f') nib.save(nib.Nifti1Image(shell_data, img.affine, img.header), args.output_dwi)
def main(): parser = build_arg_parser() args = parser.parse_args() assert_inputs_exist(parser, [args.encoding_file]) assert_outputs_exists(parser, args, [args.flipped_encoding]) indices = [str_to_index(axis) for axis in list(args.axes)] if args.fsl_bvecs: flip_fsl_bvecs(args.encoding_file, args.flipped_encoding, indices) else: flip_mrtrix_encoding_scheme(args.encoding_file, args.flipped_encoding, indices)
def main(): parser = _build_arg_parser() args = parser.parse_args() assert_inputs_exist(parser, [args.bvecs]) assert_outputs_exists(parser, args, [args.normalized_bvecs]) _, bvecs = read_bvals_bvecs(None, args.bvecs) if is_normalized_bvecs(bvecs): logging.warning('Your b-vectors are already normalized') normalize_bvecs(bvecs, args.normalized_bvecs)
def main(): parser = _build_arg_parser() args = parser.parse_args() for param in ['theta', 'curvature']: # Default was removed for consistency. if param not in args: setattr(args, param, None) assert_inputs_exist(parser, [args.sh_file, args.seed_file, args.mask_file]) assert_outputs_exists(parser, args, [args.output_file]) np.random.seed(args.seed) mask_img = nib.load(args.mask_file) mask_data = mask_img.get_data() seeds = random_seeds_from_mask( nib.load(args.seed_file).get_data(), seeds_count=args.nts if 'nts' in args else args.npv, seed_count_per_voxel='nts' not in args) # Tracking is performed in voxel space streamlines = LocalTracking(_get_direction_getter(args, mask_data), BinaryTissueClassifier(mask_data), seeds, np.eye(4), step_size=args.step_size, max_cross=1, maxlen=int(args.max_len / args.step_size) + 1, fixedstep=True, return_all=True) filtered_streamlines = (s for s in streamlines if args.min_len <= length(s) <= args.max_len) if args.compress_streamlines: filtered_streamlines = (compress_streamlines(s, args.tolerance_error) for s in filtered_streamlines) tractogram = LazyTractogram(lambda: filtered_streamlines, affine_to_rasmm=mask_img.affine) # Header with the affine/shape from mask image header = { Field.VOXEL_TO_RASMM: mask_img.affine.copy(), Field.VOXEL_SIZES: mask_img.header.get_zooms(), Field.DIMENSIONS: mask_img.shape, Field.VOXEL_ORDER: ''.join(aff2axcodes(mask_img.affine)) } # Use generator to save the streamlines on-the-fly nib.streamlines.save(tractogram, args.output_file, header=header)
def main(): parser = buildArgsParser() args = parser.parse_args() assert_inputs_exist(parser, [args.tracts, args.ref_anat]) assert_outputs_exists(parser, args, [args.out_file_name]) check_tracts_support(parser, args.tracts, args.tracts_producer) streamlines = list( load_tracts_over_grid(args.tracts, args.ref_anat, start_at_corner=True, tract_producer=args.tracts_producer)) # Compute weighting matrix taking the compression into account ref_img = nb.load(args.ref_anat) anat_dim = ref_img.get_header().get_data_shape() tract_counts_map = compute_robust_tract_counts_map(streamlines, anat_dim) voxel_volume = np.count_nonzero(tract_counts_map) resolution = np.prod(ref_img.header.get_zooms()) mm_volume = voxel_volume * resolution # Mean density weights = np.copy(tract_counts_map) weights[weights > 0] = 1 mean_density = np.average(tract_counts_map, weights=weights) tract_count = get_tract_count(streamlines) stats_names = ['tract_count', 'tract_volume', 'tract_mean_density'] means = [tract_count, mm_volume, mean_density] # Format the output. if args.out_style == 'tabular': formatted_out = format_stats_tabular(stats_names, means, stddevs=None, write_header=args.header) elif args.out_style == 'csv': formatted_out = format_stats_csv(stats_names, means, stddevs=None, write_header=args.header) if args.out_file_name is None: print(formatted_out) else: out_file = open(args.out_file_name, 'w') out_file.write(formatted_out) out_file.close()
def main(): parser = _build_arg_parser() args = parser.parse_args() logging.basicConfig(level=getattr(logging, args.log)) assert_inputs_exist(parser, [args.input]) assert_outputs_exists(parser, args, [args.output]) fname, fext = split_name_with_nii(args.output) output_folder_content = glob.glob( os.path.join(os.path.dirname(args.output), "{}_*".format(fname))) if output_folder_content and not args.overwrite: parser.error( 'Output folder contains file(s) that might be ' 'overwritten. Either remove files {}_* or use -f'.format(fname)) img = nib.load(args.input) number_of_dimensions = len(img.shape) data = img.get_data() if args.structure_connectivity < 1 or\ args.structure_connectivity > number_of_dimensions: raise ValueError('--structure_connectivity should be greater than 0 ' 'and less or equal to the number of dimension of the ' 'input data. Value found: {}'.format( args.structure_connectivity)) s = generate_binary_structure(len(img.shape), args.structure_connectivity) labeled_data, num_labels = label(data, structure=s) logging.info('Found %s labels', num_labels) img.header.set_data_dtype(labeled_data.dtype) nib.save(nib.Nifti1Image(labeled_data, img.affine, img.header), args.output) if args.split: img.header.set_data_dtype(np.uint8) num_digits_labels = len(str(num_labels + 1)) for i in xrange(1, num_labels + 1): current_label_data = np.zeros_like(data, dtype=np.uint8) current_label_data[labeled_data == i] = 1 out_name =\ os.path.join(os.path.dirname(os.path.abspath(args.output)), '{}_{}{}'.format(fname, str(i).zfill(num_digits_labels), fext)) nib.save( nib.Nifti1Image(current_label_data, img.affine, img.header), out_name)
def main(): parser = _build_args_parser() args = parser.parse_args() assert_inputs_exist(parser, [args.in_tractogram, args.transformation]) assert_outputs_exists(parser, args, [args.output_name]) wb_file = load_tractogram_with_reference(parser, args, args.in_tractogram) wb_streamlines = wb_file.streamlines model_file = load_tractogram_with_reference(parser, args, args.in_model) # Default transformation source is expected to be ANTs transfo = np.loadtxt(args.transformation) if args.inverse: transfo = np.linalg.inv(np.loadtxt(args.transformation)) model_streamlines = ArraySequence( transform_streamlines(model_file.streamlines, transfo)) rng = np.random.RandomState(args.seed) if args.input_pickle: with open(args.input_pickle, 'rb') as infile: cluster_map = pickle.load(infile) reco_obj = RecoBundles(wb_streamlines, cluster_map=cluster_map, rng=rng, verbose=args.verbose) else: reco_obj = RecoBundles(wb_streamlines, clust_thr=args.wb_clustering_thr, rng=rng, verbose=args.verbose) if args.output_pickle: with open(args.output_pickle, 'wb') as outfile: pickle.dump(reco_obj.cluster_map, outfile) _, indices = reco_obj.recognize(model_streamlines, args.model_clustering_thr, pruning_thr=args.pruning_thr, slr_num_threads=args.slr_threads) new_streamlines = wb_streamlines[indices] new_data_per_streamlines = wb_file.data_per_streamline[indices] new_data_per_points = wb_file.data_per_point[indices] if not args.no_empty or new_streamlines: sft = StatefulTractogram(new_streamlines, wb_file, Space.RASMM, data_per_streamline=new_data_per_streamlines, data_per_point=new_data_per_points) save_tractogram(sft, args.output_name)
def main(): parser = _build_arg_parser() args = parser.parse_args() assert_inputs_exist(parser, [args.tracts, args.ref_anat]) assert_outputs_exists(parser, args, [args.out]) check_tracts_support(parser, args.tracts, False) check_tracts_same_format(parser, args.tracts, args.out) # Deactivated for now. # Tested implicitely with the 2 previous tracts checks. # if not tc.is_supported(args.out): # parser.error('Format of "{0}" not supported.'.format(args.out)) filter_points(args.tracts, args.ref_anat, args.out, args.nifti_compliant_gen, args.for_nifti_compliant)
def main(): parser = _build_args_parser() args = parser.parse_args() assert_inputs_exist(parser, [args.tracts, args.ref_anat]) assert_outputs_exists(parser, args, [args.out]) check_tracts_support(parser, args.tracts, False) if not tc.is_supported(args.out): parser.error('Format of "{0}" not supported.'.format(args.out)) if not args.x and not args.y and not args.z: parser.error('No flipping axis specified.') flip_streamlines(args.tracts, args.ref_anat, args.out, args.x, args.y, args.z, args.mode)
def main(): parser = _build_args_parser() args = parser.parse_args() assert_outputs_exists(parser, args, args.output_json) data = [] layout = BIDSLayout(args.bids_folder, index_metadata=False) subjects = layout.get_subjects() for nSub in subjects: dwis = layout.get(subject=nSub, datatype='dwi', extension='nii.gz', suffix='dwi') t1s = layout.get(subject=nSub, datatype='anat', extension='nii.gz', suffix='T1w') fmaps = layout.get(subject=nSub, datatype='fmap', extension='nii.gz', suffix='epi') bvals = layout.get(subject=nSub, datatype='dwi', extension='bval', suffix='dwi') bvecs = layout.get(subject=nSub, datatype='dwi', extension='bvec', suffix='dwi') # Get associations relatives to DWIs associations = get_dwi_associations(fmaps, bvals, bvecs) # Get the data for each run of DWIs for nRun, dwi in enumerate(dwis): data.append( get_data(nSub, dwi, t1s, associations, nRun, args.readout)) with open(args.output_json, 'w') as outfile: json.dump(data, outfile, indent=4, separators=(',', ': '), sort_keys=True) # Add trailing newline for POSIX compatibility outfile.write('\n')
def main(): parser = _build_args_parser() args = parser.parse_args() assert_inputs_exist(parser, [args.tracts]) assert_outputs_exists(parser, args, [args.out]) check_tracts_support(parser, args.tracts, False) check_tracts_same_format(parser, args.tracts, args.out) if args.errorRate < 0.001 or args.errorRate > 1: logging.warn( 'You are using an error rate of {}.\nWe recommend setting it ' 'between 0.001 and 1.\n0.001 will do almost nothing to the tracts ' 'while 1 will higly compress/linearize the tracts'.format( args.errorRate)) compression_wrapper(args.tracts, args.out, args.errorRate)