Esempio n. 1
0
def main():
    parser = _build_arg_parser()
    args = parser.parse_args()

    # Checking args
    assert_inputs_exist(parser, args.in_image, args.ref)
    assert_outputs_exist(parser, args, args.out_image)
    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.in_image)

    img = nib.load(args.in_image)

    # Resampling volume
    resampled_img = resample_volume(img,
                                    ref=args.ref,
                                    res=args.resolution,
                                    iso_min=args.iso_min,
                                    interp=args.interp,
                                    enforce_dimensions=args.enforce_dimensions)

    # Saving results
    logging.debug('Saving resampled data to %s', args.out_image)
    nib.save(resampled_img, args.out_image)
Esempio n. 2
0
def main():
    parser = _build_arg_parser()
    args = parser.parse_args()

    assert_inputs_exist(parser, args.in_bundle, optional=args.reference)
    assert_outputs_exist(parser, args, args.out_img)

    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_))

    sft = load_tractogram_with_reference(parser, args, args.in_bundle)
    sft.to_vox()
    sft.to_corner()
    streamlines = sft.streamlines
    transformation, dimensions, _, _ = sft.space_attributes

    streamline_count = compute_tract_counts_map(streamlines, dimensions)

    if args.binary is not None:
        streamline_count[streamline_count > 0] = args.binary

    nib.save(
        nib.Nifti1Image(streamline_count.astype(np.int16), transformation),
        args.out_img)
Esempio n. 3
0
def main():
    parser = _build_arg_parser()
    args = parser.parse_args()

    assert_inputs_exist(parser, args.in_tractogram)
    assert_outputs_exist(parser, args, args.out_tractogram)

    if not args.out_tractogram.endswith('.trk'):
        parser.error('Output file needs to end with .trk.')

    if len(args.color) == 7:
        args.color = '0x' + args.color.lstrip('#')

    if len(args.color) == 8:
        color_int = int(args.color, 0)
        red = color_int >> 16
        green = (color_int & 0x00FF00) >> 8
        blue = color_int & 0x0000FF
    else:
        parser.error('Hexadecimal RGB color should be formatted as "#RRGGBB"'
                     ' or 0xRRGGBB.')

    sft = load_tractogram_with_reference(parser, args, args.in_tractogram)

    sft.data_per_point["color"] = [
        np.tile([red, green, blue], (len(i), 1)) for i in sft.streamlines
    ]

    sft = StatefulTractogram.from_sft(sft.streamlines,
                                      sft,
                                      data_per_point=sft.data_per_point)

    save_tractogram(sft, args.out_tractogram)
Esempio n. 4
0
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_exist(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_arg_parser()
    args = parser.parse_args()

    assert_inputs_exist(parser, [args.in_fodfs, args.in_fa, args.in_md])
    assert_outputs_exist(parser, args, [],
                         [args.max_value_output, args.mask_output])

    if args.verbose:
        logging.basicConfig(level=logging.DEBUG)

    # Load input image
    img_fODFs = nib.load(args.in_fodfs)
    fodf = img_fODFs.get_fdata(dtype=np.float32)
    affine = img_fODFs.affine
    zoom = img_fODFs.header.get_zooms()[:3]

    img_fa = nib.load(args.in_fa)
    fa = img_fa.get_fdata(dtype=np.float32)

    img_md = nib.load(args.in_md)
    md = img_md.get_fdata(dtype=np.float32)

    value, mask = get_ventricles_max_fodf(fodf, fa, md, zoom, args)

    if args.mask_output:
        img = nib.Nifti1Image(np.array(mask, 'float32'),  affine)
        nib.save(img, 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))
Esempio n. 6
0
def main():

    parser = _build_args_parser()
    args = parser.parse_args()

    assert_inputs_exist(parser, args.in_tractogram)
    assert_outputs_exist(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)
Esempio n. 7
0
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_exist(parser, args,
                         [args.map_include_corr, args.map_exclude_corr])

    map_inc = nib.load(args.map_include)
    map_inc_data = map_inc.get_fdata(dtype=np.float32)

    map_exc = nib.load(args.map_exclude)
    map_exc_data = map_exc.get_fdata(dtype=np.float32)

    additional_mask = nib.load(args.additional_mask)
    additional_mask_data = get_data_as_mask(additional_mask)

    map_inc_data[additional_mask_data > 0] = 0
    map_exc_data[additional_mask_data > 0] = 0

    # TODO Remove header or add optional argument name
    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)
Esempio n. 8
0
def main():
    parser = _build_arg_parser()
    args = parser.parse_args()

    assert_inputs_exist(parser, [args.in_metric, args.in_mask])
    assert_outputs_exist(parser, args, args.out_png)

    # Load metric image
    metric_img = nib.load(args.in_metric)
    metric_img_data = metric_img.get_fdata(dtype=np.float32)

    # Load mask image
    mask_img = nib.load(args.in_mask)
    mask_img_data = get_data_as_mask(mask_img)

    # Select value from mask
    curr_data = metric_img_data[np.where(mask_img_data > 0)]

    # Display figure
    fig, ax = plt.subplots()
    n, bins, patches = ax.hist(curr_data, bins=args.n_bins,
                               color=args.colors, alpha=0.5, rwidth=0.85)
    plt.xlabel(args.x_label)
    plt.title(args.title)

    if args.show_only:
        plt.show()
    else:
        plt.savefig(args.out_png, dpi=300, bbox_inches='tight')
def main():
    parser = _build_arg_parser()
    args = parser.parse_args()
    if args.verbose:
        logging.basicConfig(level=logging.INFO)

    # Checking args
    assert_outputs_exist(parser, args, args.out_sh)
    assert_inputs_exist(parser, args.in_sh)

    # Prepare data
    sh_img = nib.load(args.in_sh)
    data = sh_img.get_fdata(dtype=np.float32)

    sh_order, full_basis = get_sh_order_and_fullness(data.shape[-1])

    logging.info('Executing local asymmetric filtering.')
    filtered_sh = local_asym_filtering(
        data, sh_order=sh_order,
        sh_basis=args.sh_basis,
        in_full_basis=full_basis,
        out_full_basis=not(args.out_sym),
        sphere_str=args.sphere,
        dot_sharpness=args.sharpness,
        sigma=args.sigma)

    logging.info('Saving filtered SH to file {0}.'.format(args.out_sh))
    nib.save(nib.Nifti1Image(filtered_sh, sh_img.affine), args.out_sh)
def main():
    parser = _build_arg_parser()
    args = parser.parse_args()
    assert_inputs_exist(parser, [args.tractogram])
    assert_outputs_exist(parser, args, [], [args.save])

    tracts_format = detect_format(args.tractogram)
    if tracts_format is not TrkFile:
        raise ValueError("Invalid input streamline file format " +
                         "(must be trk): {0}".format(args.tractogram_filename))

    # Load files and data. TRKs can have 'same' as reference
    tractogram = load_tractogram(args.tractogram, 'same')
    # Streamlines are saved in RASMM but seeds are saved in VOX
    # This might produce weird behavior with non-iso
    tractogram.to_vox()

    streamlines = tractogram.streamlines
    if 'seeds' not in tractogram.data_per_streamline:
        parser.error('Tractogram does not contain seeds')
    seeds = tractogram.data_per_streamline['seeds']

    # Make display objects
    streamlines_actor = actor.line(streamlines)
    points = actor.dots(seeds, color=(1., 1., 1.))

    # Add display objects to canvas
    r = window.Renderer()
    r.add(streamlines_actor)
    r.add(points)

    # Show and record if needed
    if args.save is not None:
        window.record(r, out_path=args.save, size=(1000, 1000))
    window.show(r)
Esempio n. 11
0
def main():
    parser = _build_arg_parser()
    args = parser.parse_args()

    assert_inputs_exist(parser, args.in_tractogram)
    assert_outputs_exist(parser, args, args.out_tractogram)
    check_tracts_same_format(parser, args.in_tractogram, args.out_tractogram)

    if args.error_rate < 0.001 or args.error_rate > 1:
        logging.warning(
            'You are using an error rate of {}.\n'
            'We recommend setting it between 0.001 and 1.\n'
            '0.001 will do almost nothing to the streamlines\n'
            'while 1 will highly compress/linearize the streamlines'.format(
                args.error_rate))

    in_tractogram = nib.streamlines.load(args.in_tractogram, lazy_load=True)
    compressed_streamlines = compress_streamlines_wrapper(
        in_tractogram, args.error_rate)

    out_tractogram = LazyTractogram(compressed_streamlines,
                                    affine_to_rasmm=np.eye(4))
    nib.streamlines.save(out_tractogram,
                         args.out_tractogram,
                         header=in_tractogram.header)
Esempio n. 12
0
def main():
    parser = _build_arg_parser()
    args = parser.parse_args()

    assert_inputs_exist(parser, [args.in_dwi, args.in_bval, args.in_bvec])
    assert_outputs_exist(parser, args, args.out_sh)

    vol = nib.load(args.in_dwi)
    dwi = vol.get_fdata(dtype=np.float32)

    bvals, bvecs = read_bvals_bvecs(args.in_bval, args.in_bvec)
    gtab = gradient_table(args.in_bval, args.in_bvec, b0_threshold=bvals.min())

    mask = None
    if args.mask:
        mask = get_data_as_mask(nib.load(args.mask), dtype=bool)

    sh = compute_sh_coefficients(dwi,
                                 gtab,
                                 args.sh_order,
                                 args.sh_basis,
                                 args.smooth,
                                 use_attenuation=args.use_attenuation,
                                 mask=mask)

    nib.save(nib.Nifti1Image(sh.astype(np.float32), vol.affine), args.out_sh)
Esempio n. 13
0
def main():
    parser = _build_arg_parser()
    args = parser.parse_args()

    assert_inputs_exist(parser, args.in_surface, args.vts_mask)
    assert_outputs_exist(parser, args, args.out_surface)

    # Check smoothing parameters
    if args.nb_steps < 1:
        parser.error("Number of steps should be strictly positive")

    if args.step_size <= 0.0:
        parser.error("Step size should be strictly positive")

    if args.verbose:
        logging.basicConfig(level=logging.DEBUG)

    # Step size (zero for masked vertices)
    if args.vts_mask:
        mask = np.load(args.vts_mask)
        step_size_per_vts = args.step_size * mask.astype(np.float)
    else:
        step_size_per_vts = args.step_size

    mesh = load_mesh_from_file(args.in_surface)

    # Laplacian smoothing
    vts = mesh.laplacian_smooth(nb_iter=args.nb_steps,
                                diffusion_step=step_size_per_vts,
                                backward_step=True)
    mesh.set_vertices(vts)

    # Save Mesh Surface
    mesh.save(args.out_surface)
Esempio n. 14
0
def main():
    parser = _build_arg_parser()
    args = parser.parse_args()

    assert_inputs_exist(parser, args.in_bundles)
    output_streamlines_filename = '{}streamlines.trk'.format(
        args.output_prefix)
    output_voxels_filename = '{}voxels.nii.gz'.format(args.output_prefix)
    assert_outputs_exist(parser, args,
                         [output_voxels_filename, output_streamlines_filename])

    if not 0 <= args.ratio_voxels <= 1 or not 0 <= args.ratio_streamlines <= 1:
        parser.error('Ratios must be between 0 and 1.')

    fusion_streamlines = []
    if args.reference:
        reference_file = args.reference
    else:
        reference_file = args.in_bundles[0]
    sft_list = []
    for name in args.in_bundles:
        tmp_sft = load_tractogram_with_reference(parser, args, name)
        tmp_sft.to_vox()
        tmp_sft.to_corner()

        if not is_header_compatible(reference_file, tmp_sft):
            raise ValueError('Headers are not compatible.')
        sft_list.append(tmp_sft)
        fusion_streamlines.append(tmp_sft.streamlines)

    fusion_streamlines, _ = union_robust(fusion_streamlines)

    transformation, dimensions, _, _ = get_reference_info(reference_file)
    volume = np.zeros(dimensions)
    streamlines_vote = dok_matrix(
        (len(fusion_streamlines), len(args.in_bundles)))

    for i in range(len(args.in_bundles)):
        sft = sft_list[i]
        binary = compute_tract_counts_map(sft.streamlines, dimensions)
        volume[binary > 0] += 1

        if args.same_tractogram:
            _, indices = intersection_robust(
                [fusion_streamlines, sft.streamlines])
            streamlines_vote[list(indices), [i]] += 1

    if args.same_tractogram:
        real_indices = []
        ratio_value = int(args.ratio_streamlines * len(args.in_bundles))
        real_indices = np.where(
            np.sum(streamlines_vote, axis=1) >= ratio_value)[0]
        new_sft = StatefulTractogram.from_sft(fusion_streamlines[real_indices],
                                              sft_list[0])
        save_tractogram(new_sft, output_streamlines_filename)

    volume[volume < int(args.ratio_voxels * len(args.in_bundles))] = 0
    volume[volume > 0] = 1
    nib.save(nib.Nifti1Image(volume.astype(np.uint8), transformation),
             output_voxels_filename)
Esempio n. 15
0
def main():
    parser = _build_arg_parser()
    args = parser.parse_args()

    assert_inputs_exist(parser, args.input_path, args.input_bbox)
    assert_outputs_exist(parser, args, args.output_path, args.output_bbox)

    img = nib.load(args.input_path)
    if args.input_bbox:
        with open(args.input_bbox, 'rb') 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[0:3]):
                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, 'wb') as bbox_file:
                pickle.dump(wbbox, bbox_file)

    out_nifti_file = crop_nifti(img, wbbox)
    nib.save(out_nifti_file, args.output_path)
Esempio n. 16
0
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_exist(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)
Esempio n. 17
0
def main():
    parser = _build_args_parser()
    args = parser.parse_args()

    assert_inputs_exist(parser, args.in_image)
    assert_outputs_exist(parser, args, args.out_image)

    original_im = nib.load(args.in_image)

    if original_im.ndim == 4:
        if "float" in original_im.header.get_data_shape():
            scale = True
        else:
            scale = False

        converted_im = decfa(original_im, scale=scale)

        nib.save(converted_im, args.out_image)

    elif original_im.ndim == 3:
        converted_im_float = decfa_to_float(original_im)

        converted_data = converted_im_float.get_fdata()
        converted_data_int = converted_data.astype("uint8")

        converted_im = nib.Nifti1Image(converted_data_int,
                                       converted_im_float.affine)

        nib.save(converted_im, args.out_image)
Esempio n. 18
0
def main():
    parser = _build_arg_parser()
    args = parser.parse_args()

    assert_inputs_exist(parser, args.in_tractogram)
    assert_outputs_exist(parser, args, [], optional=args.out_centroids)
    assert_output_dirs_exist_and_empty(parser,
                                       args,
                                       args.out_clusters_dir,
                                       create_dir=True)

    sft = load_tractogram_with_reference(parser, args, args.in_tractogram)
    streamlines = sft.streamlines
    thresholds = [40, 30, 20, args.dist_thresh]
    clusters = qbx_and_merge(streamlines,
                             thresholds,
                             nb_pts=args.nb_points,
                             verbose=False)

    for i, cluster in enumerate(clusters):
        if len(cluster.indices) > 1:
            cluster_streamlines = itemgetter(*cluster.indices)(streamlines)
        else:
            cluster_streamlines = streamlines[cluster.indices]

        new_sft = StatefulTractogram.from_sft(cluster_streamlines, sft)
        save_tractogram(
            new_sft,
            os.path.join(args.out_clusters_dir, 'cluster_{}.trk'.format(i)))

    if args.out_centroids:
        new_sft = StatefulTractogram.from_sft(clusters.centroids, sft)
        save_tractogram(new_sft, args.out_centroids)
def main():
    parser = _build_arg_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_exist(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

    img = nib.load(args.dwi)

    outputs = extract_dwi_shell(img, bvals, bvecs, args.bvals_to_extract, tol,
                                args.block_size)
    indices, shell_data, new_bvals, new_bvecs = outputs

    logging.info("Selected indices: {}".format(indices))

    np.savetxt(args.output_bvals, new_bvals, '%d')
    np.savetxt(args.output_bvecs, new_bvecs.T, '%0.15f')
    nib.save(nib.Nifti1Image(shell_data, img.affine, img.header),
             args.output_dwi)
Esempio n. 20
0
def main():
    parser = _build_arg_parser()
    args = parser.parse_args()
    if args.verbose:
        logging.basicConfig(level=logging.INFO)

    assert_inputs_exist(parser, args.in_sh, args.mask)
    assert_outputs_exist(parser, args, args.out_bingham)

    sh_im = nib.load(args.in_sh)
    data = sh_im.get_fdata()
    mask = get_data_as_mask(nib.load(args.mask), dtype=bool)\
        if args.mask else None

    # validate number of processes
    nbr_processes = validate_nbr_processes(parser, args)
    logging.info('Number of processes: {}'.format(nbr_processes))

    t0 = time.perf_counter()
    logging.info('Fitting Bingham functions.')
    bingham = bingham_fit_sh(data, args.max_lobes,
                             abs_th=args.at, rel_th=args.rt,
                             min_sep_angle=args.min_sep_angle,
                             max_fit_angle=args.max_fit_angle,
                             mask=mask,
                             nbr_processes=nbr_processes)
    t1 = time.perf_counter()
    logging.info('Fitting done in (s): {0}'.format(t1 - t0))
    nib.save(nib.Nifti1Image(bingham, sh_im.affine), args.out_bingham)
def main():
    parser = _build_arg_parser()
    args = parser.parse_args()

    assert_inputs_exist(parser, [args.input_sh])
    assert_outputs_exist(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)
Esempio n. 22
0
def main():
    parser = _build_arg_parser()
    args = parser.parse_args()

    assert_inputs_exist(parser, [args.moving_tractogram,
                                 args.static_tractogram])

    if args.only_rigid:
        matrix_filename = os.path.splitext(args.out_name)[0] + '_rigid.txt'
    else:
        matrix_filename = os.path.splitext(args.out_name)[0] + '_affine.txt'

    assert_outputs_exist(parser, args, matrix_filename, args.out_name)

    sft_moving = load_tractogram_with_reference(parser, args,
                                                args.moving_tractogram,
                                                arg_name='moving_tractogram')

    sft_static = load_tractogram_with_reference(parser, args,
                                                args.static_tractogram,
                                                arg_name='static_tractogram')

    if args.only_rigid:
        transformation_type = 'rigid'
    else:
        transformation_type = 'affine'

    ret = whole_brain_slr(sft_moving.streamlines,
                          sft_static.streamlines,
                          x0=transformation_type,
                          maxiter=150,
                          verbose=args.verbose)
    _, transfo, _, _ = ret

    np.savetxt(matrix_filename, transfo)
def main():
    parser = _build_args_parser()
    args = parser.parse_args()
    assert_inputs_exist(parser, [args.tractogram])
    assert_outputs_exist(parser, args, [], [args.save])

    tracts_format = detect_format(args.tractogram)
    if tracts_format is not TrkFile:
        raise ValueError("Invalid input streamline file format " +
                         "(must be trk): {0}".format(args.tractogram_filename))

    # Load files and data
    trk = TrkFile.load(args.tractogram)
    tractogram = trk.tractogram
    streamlines = tractogram.streamlines
    if 'seeds' not in tractogram.data_per_streamline:
        parser.error('Tractogram does not contain seeds')
    seeds = tractogram.data_per_streamline['seeds']

    # Make display objects
    streamlines_actor = actor.line(streamlines)
    points = actor.dots(seeds, color=(1., 1., 1.))

    # Add display objects to canvas
    r = window.Renderer()
    r.add(streamlines_actor)
    r.add(points)

    # Show and record if needed
    if args.save is not None:
        window.record(r, out_path=args.save, size=(1000, 1000))
    window.show(r)
Esempio n. 24
0
def main():
    parser = _build_arg_parser()
    args = parser.parse_args()

    assert_inputs_exist(parser, args.in_json)
    assert_outputs_exist(parser, args, args.out_json)

    out_dict = {}
    for in_file in args.in_json:
        with open(in_file, 'r') as json_file:
            in_dict = json.load(json_file)
            if args.remove_parent_key:
                in_dict = list(in_dict.values())[0]
            if args.keep_separate:
                out_dict[os.path.splitext(in_file)[0]] = in_dict
            else:
                out_dict = _merge_dict(out_dict,
                                       in_dict,
                                       no_list=args.no_list,
                                       recursive=args.recursive)

    if args.average_last_layer:
        out_dict = _average_dict(out_dict)

    with open(args.out_json, 'w') as outfile:
        if args.add_parent_key:
            out_dict = {args.add_parent_key: out_dict}
        json.dump(out_dict,
                  outfile,
                  indent=args.indent,
                  sort_keys=args.sort_keys)
Esempio n. 25
0
def main():
    parser = _build_arg_parser()
    args = parser.parse_args()

    assert_inputs_exist(parser, args.in_tractogram)
    assert_outputs_exist(parser, args, args.out_tractogram)

    log_level = logging.WARNING
    if args.verbose:
        log_level = logging.DEBUG
    logging.basicConfig(level=log_level)

    sft = load_tractogram_with_reference(parser, args, args.in_tractogram)
    smoothed_streamlines = []
    for streamline in sft.streamlines:
        if args.gaussian:
            tmp_streamlines = smooth_line_gaussian(streamline, args.gaussian)
        else:
            tmp_streamlines = smooth_line_spline(streamline, args.spline[0],
                                                 args.spline[1])

        if args.error_rate:
            smoothed_streamlines.append(
                compress_streamlines(tmp_streamlines, args.error_rate))

    smoothed_sft = StatefulTractogram.from_sft(
        smoothed_streamlines, sft, data_per_streamline=sft.data_per_streamline)
    save_tractogram(smoothed_sft, args.out_tractogram)
Esempio n. 26
0
def _parse_args(parser):
    args = parser.parse_args()
    inputs = []
    output = []
    inputs.append(args.in_fodf)
    if args.output:
        output.append(args.output)
    else:
        if args.silent:
            parser.error('Silent mode is enabled but no output is specified.'
                         'Specify an output with --output to use silent mode.')
    if args.mask:
        inputs.append(args.mask)
    if args.background:
        inputs.append(args.background)

    if args.peaks:
        if args.full_basis:
            # FURY doesn't support asymmetric peaks visualization
            warnings.warn(
                'Asymmetric peaks visualization is not supported '
                'by FURY. Peaks shown as symmetric peaks.', UserWarning)
        inputs.append(args.peaks)
        if args.peaks_values:
            inputs.append(args.peaks_values)
    else:
        if args.peaks_values:
            parser.error('Peaks values image supplied without peaks. Specify '
                         'a peaks image with --peaks to use this feature.')

    assert_inputs_exist(parser, inputs)
    assert_outputs_exist(parser, args, output)

    return args
Esempio n. 27
0
def main():
    """Parse arguments, generate hdf5 dataset and save it on disk."""
    p = _parse_args()
    args = p.parse_args()

    # Initialize logger
    logging.basicConfig(level=str(args.logging).upper())

    # Silencing SFT's logger if our logging is in DEBUG mode, because it
    # typically produces a lot of outputs!
    set_sft_logger_level('WARNING')

    # Verify that dwi_ml_ready folder is found
    if not Path(args.dwi_ml_ready_folder).is_dir():
        raise ValueError('The dwi_ml_ready folder was not found: {}'.format(
            args.dwi_ml_ready_folder))
    assert_inputs_exist(
        p, [args.config_file],
        [args.training_subjs, args.validation_subjs, args.testing_subjs])
    # check hdf extension
    _, ext = os.path.splitext(args.out_hdf5_file)
    if ext == '':
        args.out_hdf5_file += '.hdf5'
    elif ext != '.hdf5':
        raise p.error("The hdf5 file's extension should be .hdf5, but "
                      "received {}".format(ext))
    assert_outputs_exist(p, args, args.out_hdf5_file)

    # Prepare creator and load config file.
    creator = prepare_hdf5_creator(args)

    # Create dataset from config and save
    with Timer("\nCreating database...", newline=True, color='green'):
        creator.create_database()
def main():
    parser = _build_arg_parser()
    args = parser.parse_args()

    assert_inputs_exist(parser, [args.input, args.fa, args.md])
    assert_outputs_exist(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))
Esempio n. 29
0
def _parse_args(parser):
    args = parser.parse_args()
    inputs = []
    output = []
    inputs.append(args.in_fodf)
    if args.output:
        output.append(args.output)
    else:
        if args.silent:
            parser.error('Silent mode is enabled but no output is specified.'
                         'Specify an output with --output to use silent mode.')
    if args.mask:
        inputs.append(args.mask)
    if args.background:
        inputs.append(args.background)

    if args.peaks:
        inputs.append(args.peaks)
        if args.peaks_values:
            inputs.append(args.peaks_values)
    else:
        if args.peaks_values:
            parser.error('Peaks values image supplied without peaks. Specify '
                         'a peaks image with --peaks to use this feature.')

    assert_inputs_exist(parser, inputs)
    assert_outputs_exist(parser, args, output)

    return args
def main():

    parser = _build_args_parser()
    args = parser.parse_args()

    assert_inputs_exist(parser, args.in_tractogram)
    assert_outputs_exist(parser, args, args.out_tractogram)

    if args.verbose:
        logging.basicConfig(level=logging.DEBUG)

    sft = load_tractogram_with_reference(parser, args, args.in_tractogram)

    new_streamlines, new_per_point, new_per_streamline = filter_streamlines_by_length(
        sft, args.minL, args.maxL)

    new_sft = StatefulTractogram(new_streamlines,
                                 sft,
                                 Space.RASMM,
                                 data_per_streamline=new_per_streamline,
                                 data_per_point=new_per_point)

    if not new_streamlines:
        if args.no_empty:
            logging.debug("The file {} won't be written "
                          "(0 streamline).".format(args.out_tractogram))

            return

        logging.debug('The file {} contains 0 streamline'.format(
            args.out_tractogram))

    save_tractogram(new_sft, args.out_tractogram)