def get_transform_space_params(registration_config, destination_image): atlas = brainio.load_nii(str(destination_image), as_array=False) atlas_scale = atlas.header.get_zooms() atlas_pixel_sizes = get_atlas_pixel_sizes(registration_config) transformation_matrix = np.eye(4) for i, axis in enumerate(("x", "y", "z")): transformation_matrix[i, i] = atlas_pixel_sizes[axis] return atlas_scale, transformation_matrix
def analysis_run(args, file_name="summary_cell_counts.csv"): args = prep_atlas_conf(args) atlas = brainio.load_any(args.paths.registered_atlas_path) hemisphere = brainio.load_any(args.paths.hemispheres_atlas_path) cells = get_cells_data( args.paths.classification_out_file, cells_only=args.cells_only, ) max_coords = get_max_coords(cells) # Useful for debugging dimensions structures_reference_df = load_structures_as_df(get_structures_path()) atlas_pixel_sizes = get_atlas_pixel_sizes(args.atlas_config) sample_pixel_sizes = args.x_pixel_um, args.y_pixel_um, args.z_pixel_um scales = get_scales(sample_pixel_sizes, atlas_pixel_sizes, args.scale_cell_coordinates) structures_with_cells = set() for i, cell in enumerate(tqdm(cells)): transform_cell_coords(atlas, cell, scales) structure_id = get_structure_from_coordinates( atlas, cell, max_coords, order=args.coordinates_order, structures_reference_df=structures_reference_df, ) if structure_id is not None: cell.structure_id = structure_id structures_with_cells.add(structure_id) else: continue cell.hemisphere = get_structure_from_coordinates( hemisphere, cell, max_coords, order=args.coordinates_order) sorted_cell_numbers = get_cells_nbs_df(cells, structures_reference_df, structures_with_cells) combined_hemispheres = combine_df_hemispheres(sorted_cell_numbers) df = calculate_densities(combined_hemispheres, args.paths.volume_csv_path) df = sanitise_df(df) if not os.path.exists(args.output_dir): os.makedirs(args.output_dir) output_file = os.path.join(args.output_dir, file_name) df.to_csv(output_file, index=False)
def summarise_brain_regions(label_layers, filename): summaries = [] for label_layer in label_layers: summaries.append(summarise_single_brain_region(label_layer)) result = pd.concat(summaries) volume_header = "volume_mm3" length_columns = [ "x_min_um", "y_min_um", "z_min_um", "x_max_um", "y_max_um", "z_max_um", "x_center_um", "y_center_um", "z_center_um", ] result.columns = ["region"] + [volume_header] + length_columns atlas_pixel_sizes = get_atlas_pixel_sizes(source_custom_config_amap()) voxel_volume = get_voxel_volume(source_custom_config_amap()) / (1000**3) result[volume_header] = result[volume_header] * voxel_volume for header in length_columns: for dim in atlas_pixel_sizes.keys(): if header.startswith(dim): scale = float(atlas_pixel_sizes[dim]) assert scale > 0 result[header] = result[header] * scale result.to_csv(filename, index=False)
def xml_crop(args, df_query="name"): args = prep_atlas_conf(args) if args.structures_file_path is None: args.structures_file_path = get_structures_path() reference_struct_df = pd.read_csv(get_structures_path()) curate_struct_df = pd.read_csv(args.structures_file_path) curate_struct_df = reference_struct_df[ reference_struct_df[df_query].isin(curate_struct_df[df_query]) ] curated_ids = list(curate_struct_df["structure_id_path"]) atlas = brainio.load_any(args.registered_atlas_path) hemisphere = brainio.load_any(args.hemispheres_atlas_path) structures_reference_df = load_structures_as_df(get_structures_path()) atlas_pixel_sizes = get_atlas_pixel_sizes(args.atlas_config) sample_pixel_sizes = args.x_pixel_um, args.y_pixel_um, args.z_pixel_um scales = cells_regions.get_scales(sample_pixel_sizes, atlas_pixel_sizes) destination_folder = os.path.join(args.xml_dir, "xml_crop") if not os.path.exists(destination_folder): os.makedirs(destination_folder) xml_names = [f for f in os.listdir(args.xml_dir) if f.endswith(".xml")] xml_paths = [os.path.join(args.xml_dir, f) for f in xml_names] for idx, xml_path in enumerate(xml_paths): print("Curating file: {}".format(xml_names[idx])) cells = cells_regions.get_cells_data( xml_path, cells_only=args.cells_only, ) max_coords = cells_regions.get_max_coords(cells) curated_cells = [] for i, cell in enumerate(cells): cells_regions.transform_cell_coords(atlas, cell, scales) structure_id = cells_regions.get_structure_from_coordinates( atlas, cell, max_coords, order=args.coordinates_order, structures_reference_df=structures_reference_df, ) if structure_id in curated_ids: if args.hemisphere_query in [1, 2]: hemisphere = cells_regions.get_structure_from_coordinates( hemisphere, cell, max_coords, order=args.coordinates_order, ) if hemisphere is args.hemisphere_query: curated_cells.append(cell) else: curated_cells.append(cell) cells_to_xml( curated_cells, os.path.join(destination_folder, xml_names[idx]), artifact_keep=True, ) print("Done!")
amap_output_dir = Path(amap_output_dir) annotations_image = load_any(amap_output_dir / reg_paths.ANNOTATIONS) midpoint = int(annotations_image.shape[0] // 2) hemispheres_image = load_any(amap_output_dir / reg_paths.HEMISPHERES) sub_region_values = list(sub_regions["id"]) region_mask = np.isin(annotations_image, sub_region_values) left_region_mask = region_mask * (hemispheres_image == left_hemisphere_value) right_region_mask = region_mask * (hemispheres_image == right_hemisphere_value) left_region_summary = regionprops(left_region_mask.astype(np.int8))[0] right_region_summary = regionprops(right_region_mask.astype(np.int8))[0] atlas_pixel_sizes = get_atlas_pixel_sizes(source_custom_config_amap()) results_dict = { "x_min_um_left": left_region_summary.bbox[0] * int(atlas_pixel_sizes["x"]), "y_min_um_left": left_region_summary.bbox[1] * int(atlas_pixel_sizes["y"]), "z_min_um_left": left_region_summary.bbox[2] * int(atlas_pixel_sizes["z"]), "x_max_um_left": left_region_summary.bbox[3] * int(atlas_pixel_sizes["x"]), "y_max_um_left": left_region_summary.bbox[4] * int(atlas_pixel_sizes["y"]), "z_max_um_left": left_region_summary.bbox[5] * int(atlas_pixel_sizes["z"]), "x_center_um_left":
def main(): start_time = datetime.now() print("Starting ROI transformation") args = get_parser().parse_args() rois = args.rois print(f"ROI file is: {rois}") if args.registration_config is None: args.registration_config = source_custom_config_cellfinder() atlas = Atlas(args.registration_config) source_image = args.reg_dir / SOURCE_IMAGE_NAME print(f"Source image is: {source_image}") destination_image = args.reg_dir / atlas.atlas_conf["default_brain_name"] print(f"Destination image is: {destination_image}") control_point_file = args.reg_dir / DEFAULT_CONTROL_POINT_FILE print(f"Transformation file is: {control_point_file}") if args.output_filename is None: output_filename = rois.parent / DEFAULT_OUTPUT_FILE_NAME temp_output_filename = rois.parent / DEFAULT_TEMP_FILE_NAME log_file_path = rois.parent / "roi_transform_log.txt" error_file_path = rois.parent / "roi_transform_error.txt" else: output_filename = args.output_filename temp_output_filename = ( args.output_filename.parent / DEFAULT_TEMP_FILE_NAME ) log_file_path = args.output_filename.parent / "roi_transform_log.txt" error_file_path = ( args.output_filename.parent / "roi_transform_error.txt" ) if not output_filename.parent.exists(): output_filename.parent.mkdir() print(f"Output file is: {output_filename}") atlas = brainio.load_nii(str(destination_image), as_array=False) atlas_scale = atlas.header.get_zooms() atlas_pixel_sizes = get_atlas_pixel_sizes(args.registration_config) transformation_matrix = np.eye(4) for i, axis in enumerate(("x", "y", "z")): transformation_matrix[i, i] = atlas_pixel_sizes[axis] transform_rois( rois, source_image, destination_image, control_point_file, output_filename, temp_output_filename, log_file_path, error_file_path, roi_reference_image=args.reference_image, selem_size=args.selem_size, nii_scale=atlas_scale, transformation_matrix=transformation_matrix, debug=args.debug, z_filter_padding=args.z_filter_padding, ) print("Finished. Total time taken: {}".format(datetime.now() - start_time))
def get_transformation_matrix(self): atlas_pixel_sizes = get_atlas_pixel_sizes(self._atlas_config) transformation_matrix = np.eye(4) for i, axis in enumerate(("x", "y", "z")): transformation_matrix[i, i] = atlas_pixel_sizes[axis] self.transformation_matrix = transformation_matrix