synapse_net.tools.volume_reader
1import os 2from typing import Callable, List, Optional, Sequence, Union 3 4from elf.io import open_file, is_dataset 5from napari.types import LayerData 6from synapse_net.file_utils import read_mrc 7 8 9PathLike = str 10PathOrPaths = Union[PathLike, Sequence[PathLike]] 11ReaderFunction = Callable[[PathOrPaths], List[LayerData]] 12 13 14def get_reader(path: PathOrPaths) -> Optional[ReaderFunction]: 15 # If we recognize the format, we return the actual reader function. 16 if isinstance(path, str) and path.endswith((".mrc", ".rec", ".h5")): 17 return read_image_volume 18 # Otherwise we return None. 19 return None 20 21 22def _read_mrc(path, fname): 23 data, voxel_size = read_mrc(path) 24 metadata = {"file_path": path, "voxel_size": voxel_size} 25 layer_attributes = { 26 "name": fname, 27 "colormap": "gray", 28 "metadata": metadata 29 } 30 return [(data, layer_attributes)] 31 32 33# For hdf5 files we read the full content. 34def _read_hdf5(path): 35 return_data = [] 36 37 def visitor(name, obj): 38 if is_dataset(obj): 39 data = obj[:] 40 attributes = {"name": name} 41 if str(data.dtype) in ("int32", "uint32", "int64", "uint64"): 42 layer_type = "labels" 43 else: 44 layer_type = "image" 45 attributes["colormap"] = "gray" 46 47 return_data.append((data, attributes, layer_type)) 48 49 with open_file(path, mode="r") as f: 50 f.visititems(visitor) 51 52 return return_data 53 54 55def read_image_volume(path: PathOrPaths) -> List[LayerData]: 56 fname = os.path.basename(path) 57 fname, ext = os.path.splitext(fname) 58 59 try: 60 if ext in (".mrc", ".rec"): 61 return _read_mrc(path, fname) 62 else: # This is an hdf5 file 63 return _read_hdf5(path) 64 65 except Exception as e: 66 print(f"Failed to read file: {e}") 67 return
PathLike =
<class 'str'>
PathOrPaths =
typing.Union[str, typing.Sequence[str]]
ReaderFunction =
typing.Callable[[typing.Union[str, typing.Sequence[str]]], typing.List[typing.Union[tuple[typing.Any], tuple[typing.Any, collections.abc.Mapping], tuple[typing.Any, collections.abc.Mapping, typing.Literal['graph', 'image', 'labels', 'points', 'shapes', 'surface', 'tracks', 'vectors']]]]]
def
get_reader( path: Union[str, Sequence[str]]) -> Optional[Callable[[Union[str, Sequence[str]]], List[Union[tuple[Any], tuple[Any, Mapping], tuple[Any, Mapping, Literal['graph', 'image', 'labels', 'points', 'shapes', 'surface', 'tracks', 'vectors']]]]]]:
def
read_image_volume( path: Union[str, Sequence[str]]) -> List[Union[tuple[Any], tuple[Any, Mapping], tuple[Any, Mapping, Literal['graph', 'image', 'labels', 'points', 'shapes', 'surface', 'tracks', 'vectors']]]]:
56def read_image_volume(path: PathOrPaths) -> List[LayerData]: 57 fname = os.path.basename(path) 58 fname, ext = os.path.splitext(fname) 59 60 try: 61 if ext in (".mrc", ".rec"): 62 return _read_mrc(path, fname) 63 else: # This is an hdf5 file 64 return _read_hdf5(path) 65 66 except Exception as e: 67 print(f"Failed to read file: {e}") 68 return