示例#1
0
def load_cubes_in_dir(directory):
    cube_list = os.listdir(directory)
    cubes = []
    for file in cube_list:
        file_path = os.path.join(directory, file)
        cubes.append(imio.load_any(file_path))
    return cubes
示例#2
0
    def read(self, filename: str) -> Optional[LocalAtlasReaderData]:
        path = Path(filename)
        volume = imio.load_any(str(path))

        return LocalAtlasReaderData(
            source="File",
            name=path.name,
            registration_volume=volume,
        )
示例#3
0
def get_lateralised_atlas(
    atlas_path,
    hemispheres_path,
    left_hemisphere_value=2,
    right_hemisphere_value=1,
):
    atlas = imio.load_any(atlas_path)
    hemispheres = imio.load_any(hemispheres_path)

    atlas_left, atlas_right = lateralise_atlas(
        atlas,
        hemispheres,
        left_hemisphere_value=left_hemisphere_value,
        right_hemisphere_value=right_hemisphere_value,
    )

    unique_vals_left, counts_left = np.unique(atlas_left, return_counts=True)
    unique_vals_right, counts_right = np.unique(atlas_right,
                                                return_counts=True)
    return unique_vals_left, unique_vals_right, counts_left, counts_right
示例#4
0
def boundaries(registered_atlas, boundaries_out_path):
    """
    Generate the boundary image, which is the border between each segmentation
    region. Useful for overlaying on the raw image to assess the registration
    and segmentation

    :param registered_atlas: The registered atlas
    :param boundaries_out_path: Path to save the boundary image
    """
    atlas_img = imio.load_any(registered_atlas)
    boundaries_image = find_boundaries(atlas_img,
                                       mode="inner").astype(np.int8,
                                                            copy=False)
    logging.debug("Saving segmentation boundary image")
    imio.to_tiff(
        boundaries_image,
        boundaries_out_path,
    )
示例#5
0
文件: run.py 项目: pakanlab/brainreg
def run_niftyreg(
    registration_output_folder,
    paths,
    atlas,
    atlas_pixel_sizes,
    target_brain,
    n_processes,
    additional_images_downsample,
    DATA_ORIENTATION,
    ATLAS_ORIENTATION,
    niftyreg_args,
    x_scaling,
    y_scaling,
    z_scaling,
    load_parallel,
    sort_input_file,
    n_free_cpus,
    debug=False,
):

    niftyreg_directory = os.path.join(registration_output_folder, "niftyreg")

    niftyreg_paths = NiftyRegPaths(niftyreg_directory)

    save_nii(atlas.hemispheres, atlas_pixel_sizes, niftyreg_paths.hemispheres)

    save_nii(atlas.annotation, atlas_pixel_sizes, niftyreg_paths.annotations)

    reference = preprocess.filter_image(atlas.reference)
    save_nii(reference, atlas_pixel_sizes, niftyreg_paths.brain_filtered)

    save_nii(target_brain, atlas_pixel_sizes, niftyreg_paths.downsampled_brain)
    imio.to_tiff(target_brain, paths.downsampled_brain_path)

    target_brain = preprocess.filter_image(target_brain)
    save_nii(
        target_brain,
        atlas_pixel_sizes,
        niftyreg_paths.downsampled_filtered,
    )

    logging.info("Registering")

    registration_params = RegistrationParams(
        affine_n_steps=niftyreg_args.affine_n_steps,
        affine_use_n_steps=niftyreg_args.affine_use_n_steps,
        freeform_n_steps=niftyreg_args.freeform_n_steps,
        freeform_use_n_steps=niftyreg_args.freeform_use_n_steps,
        bending_energy_weight=niftyreg_args.bending_energy_weight,
        grid_spacing=niftyreg_args.grid_spacing,
        smoothing_sigma_reference=niftyreg_args.smoothing_sigma_reference,
        smoothing_sigma_floating=niftyreg_args.smoothing_sigma_floating,
        histogram_n_bins_floating=niftyreg_args.histogram_n_bins_floating,
        histogram_n_bins_reference=niftyreg_args.histogram_n_bins_reference,
    )
    brain_reg = BrainRegistration(
        niftyreg_paths,
        registration_params,
        n_processes=n_processes,
    )

    logging.info("Starting affine registration")
    brain_reg.register_affine()

    logging.info("Starting freeform registration")
    brain_reg.register_freeform()

    logging.info("Starting segmentation")
    brain_reg.segment()

    logging.info("Segmenting hemispheres")
    brain_reg.register_hemispheres()

    logging.info("Generating inverse (sample to atlas) transforms")
    brain_reg.generate_inverse_transforms()

    logging.info("Transforming image to standard space")
    brain_reg.transform_to_standard_space(
        niftyreg_paths.downsampled_brain,
        niftyreg_paths.downsampled_brain_standard_space,
    )

    logging.info("Generating deformation field")
    brain_reg.generate_deformation_field(niftyreg_paths.deformation_field)

    logging.info("Exporting images as tiff")
    imio.to_tiff(
        imio.load_any(niftyreg_paths.registered_atlas_path).astype(np.uint32,
                                                                   copy=False),
        paths.registered_atlas,
    )
    imio.to_tiff(
        imio.load_any(niftyreg_paths.registered_hemispheres_img_path).astype(
            np.uint8, copy=False),
        paths.registered_hemispheres,
    )
    imio.to_tiff(
        imio.load_any(niftyreg_paths.downsampled_brain_standard_space).astype(
            np.uint16, copy=False),
        paths.downsampled_brain_standard_space,
    )

    del atlas
    del reference
    del target_brain

    deformation_image = imio.load_any(niftyreg_paths.deformation_field)
    imio.to_tiff(
        deformation_image[..., 0, 0].astype(np.uint32, copy=False),
        paths.deformation_field_0,
    )
    imio.to_tiff(
        deformation_image[..., 0, 1].astype(np.uint32, copy=False),
        paths.deformation_field_1,
    )
    imio.to_tiff(
        deformation_image[..., 0, 2].astype(np.uint32, copy=False),
        paths.deformation_field_2,
    )

    if additional_images_downsample:
        logging.info("Saving additional downsampled images")
        for name, filename in additional_images_downsample.items():
            logging.info(f"Processing: {name}")

            downsampled_brain_path = os.path.join(registration_output_folder,
                                                  f"downsampled_{name}.tiff")
            tmp_downsampled_brain_path = os.path.join(
                niftyreg_paths.niftyreg_directory,
                f"downsampled_{name}.nii",
            )
            downsampled_brain_standard_path = os.path.join(
                registration_output_folder,
                f"downsampled_standard_{name}.tiff")
            tmp_downsampled_brain_standard_path = os.path.join(
                niftyreg_paths.niftyreg_directory,
                f"downsampled_standard_{name}.nii",
            )

            # do the tiff part at the beginning
            downsampled_brain = imio.load_any(
                filename,
                x_scaling,
                y_scaling,
                z_scaling,
                load_parallel=load_parallel,
                sort_input_file=sort_input_file,
                n_free_cpus=n_free_cpus,
            )

            downsampled_brain = bg.map_stack_to(
                DATA_ORIENTATION, ATLAS_ORIENTATION,
                downsampled_brain).astype(np.uint16, copy=False)

            save_nii(
                downsampled_brain,
                atlas_pixel_sizes,
                tmp_downsampled_brain_path,
            )
            imio.to_tiff(downsampled_brain, downsampled_brain_path)

            logging.info("Transforming to standard space")

            brain_reg.transform_to_standard_space(
                tmp_downsampled_brain_path,
                tmp_downsampled_brain_standard_path,
            )

            imio.to_tiff(
                imio.load_any(tmp_downsampled_brain_standard_path).astype(
                    np.uint16, copy=False),
                downsampled_brain_standard_path,
            )

    if not debug:
        logging.info("Deleting intermediate niftyreg files")
        delete_directory_contents(niftyreg_directory)
        os.rmdir(niftyreg_directory)
示例#6
0
def main(
    atlas,
    data_orientation,
    target_brain_path,
    paths,
    niftyreg_args,
    x_pixel_um=0.02,
    y_pixel_um=0.02,
    z_pixel_um=0.05,
    n_free_cpus=2,
    sort_input_file=False,
    additional_images_downsample=None,
    backend="niftyreg",
    debug=False,
):

    n_processes = get_num_processes(min_free_cpu_cores=n_free_cpus)
    load_parallel = n_processes > 1

    # TODO: check orientation of atlas voxel sizes
    atlas_pixel_sizes = {
        "x": atlas.metadata["resolution"][0],
        "y": atlas.metadata["resolution"][1],
        "z": atlas.metadata["resolution"][2],
    }

    scaling_rounding_decimals = 5

    x_scaling = round(x_pixel_um / atlas_pixel_sizes["x"],
                      scaling_rounding_decimals)
    y_scaling = round(y_pixel_um / atlas_pixel_sizes["y"],
                      scaling_rounding_decimals)
    z_scaling = round(z_pixel_um / atlas_pixel_sizes["z"],
                      scaling_rounding_decimals)

    logging.info("Loading raw image data")

    target_brain = imio.load_any(
        target_brain_path,
        x_scaling,
        y_scaling,
        z_scaling,
        load_parallel=load_parallel,
        sort_input_file=sort_input_file,
        n_free_cpus=n_free_cpus,
    )

    target_brain = bg.map_stack_to(data_orientation,
                                   atlas.metadata["orientation"], target_brain)

    if backend == "niftyreg":
        run_niftyreg(
            paths.registration_output_folder,
            paths,
            atlas,
            atlas_pixel_sizes,
            target_brain,
            n_processes,
            additional_images_downsample,
            data_orientation,
            atlas.metadata["orientation"],
            niftyreg_args,
            x_scaling,
            y_scaling,
            z_scaling,
            load_parallel,
            sort_input_file,
            n_free_cpus,
            debug=debug,
        )

    logging.info("Calculating volumes of each brain area")
    calculate_volumes(
        atlas,
        paths.registered_atlas,
        paths.registered_hemispheres,
        paths.volume_csv_path,
        # for all brainglobe atlases
        left_hemisphere_value=1,
        right_hemisphere_value=2,
    )

    logging.info("Generating boundary image")
    boundaries(
        paths.registered_atlas,
        paths.boundaries_file_path,
    )

    logging.info(f"brainreg completed. Results can be found here: "
                 f"{paths.registration_output_folder}")
示例#7
0
def main(
    atlas,
    data_orientation,
    target_brain_path,
    paths,
    voxel_sizes,
    niftyreg_args,
    n_free_cpus=2,
    sort_input_file=False,
    additional_images_downsample=None,
    backend="niftyreg",
    scaling_rounding_decimals=5,
    debug=False,
):
    atlas = BrainGlobeAtlas(atlas)
    source_space = bg.AnatomicalSpace(data_orientation)

    scaling = []
    for idx, axis in enumerate(atlas.space.axes_order):
        scaling.append(
            round(
                float(voxel_sizes[idx]) /
                atlas.resolution[atlas.space.axes_order.index(
                    source_space.axes_order[idx])],
                scaling_rounding_decimals,
            ))

    n_processes = get_num_processes(min_free_cpu_cores=n_free_cpus)
    load_parallel = n_processes > 1

    logging.info("Loading raw image data")

    target_brain = imio.load_any(
        target_brain_path,
        scaling[1],
        scaling[2],
        scaling[0],
        load_parallel=load_parallel,
        sort_input_file=sort_input_file,
        n_free_cpus=n_free_cpus,
    )

    target_brain = bg.map_stack_to(data_orientation,
                                   atlas.metadata["orientation"], target_brain)

    if backend == "niftyreg":
        run_niftyreg(
            paths.registration_output_folder,
            paths,
            atlas,
            target_brain,
            n_processes,
            additional_images_downsample,
            data_orientation,
            atlas.metadata["orientation"],
            niftyreg_args,
            scaling,
            load_parallel,
            sort_input_file,
            n_free_cpus,
            debug=debug,
        )

    logging.info("Calculating volumes of each brain area")
    calculate_volumes(
        atlas,
        paths.registered_atlas,
        paths.registered_hemispheres,
        paths.volume_csv_path,
        # for all brainglobe atlases
        left_hemisphere_value=1,
        right_hemisphere_value=2,
    )

    logging.info("Generating boundary image")
    boundaries(
        paths.registered_atlas,
        paths.boundaries_file_path,
    )

    logging.info(f"brainreg completed. Results can be found here: "
                 f"{paths.registration_output_folder}")