def test_match_ext(self): self.assertEqual( libmag.match_ext("foo1/bar1/item1.ext1", "foo2/bar2/item2.ext2"), "foo2/bar2/item2.ext1") # if there is no extension in the path to match, it will retain its own extension self.assertEqual( libmag.match_ext("foo1/bar1/item1", "foo2/bar2/item2.ext2"), "foo2/bar2/item2.ext2") self.assertEqual( libmag.match_ext("foo1/bar1/item1.ext1", "foo2/bar2/item2"), "foo2/bar2/item2.ext1") self.assertEqual( libmag.match_ext("foo1/bar1/item1", "foo2/bar2/item2"), "foo2/bar2/item2")
def load_registered_img(img_path, reg_name, get_sitk=False, replace=None, return_path=False): """Load atlas-based image that has been registered to another image. Args: img_path: Path as had been given to generate the registered images, with the parent path of the registered images and base name of the original image. reg_name: Atlas image suffix to open. get_sitk: True if the image should be returned as a SimpleITK image; defaults to False, in which case the corresponding Numpy array will be extracted instead. replace: Numpy image with which to replace and overwrite the loaded image. Defaults to None, in which case no replacement will take place. return_path (bool): True to return the path from which the image was loaded; defaults to False. Returns: :obj:`np.ndarray`: The atlas-based image as a Numpy array, or a :obj:`sitk.Image` object if ``get_sitk`` is True. Also returns the loaded path if ``return_path`` is True. Raises: ``FileNotFoundError`` if the path cannot be found. """ # prioritize registered image extension matched to that of main image reg_img_path = reg_out_path(img_path, reg_name, True) reg_img, reg_img_path = read_sitk(reg_img_path) if reg_img is None: # fallback to loading barren reg_name from img_path's dir reg_img_path = os.path.join(os.path.dirname(img_path), libmag.match_ext(img_path, reg_name)) reg_img, reg_img_path = read_sitk(reg_img_path) if reg_img is None: raise FileNotFoundError( "could not find registered image from {} and {}".format( img_path, os.path.splitext(reg_name)[0])) if replace is not None: reg_img = replace_sitk_with_numpy(reg_img, replace) sitk.WriteImage(reg_img, reg_img_path, False) print("replaced {} with current registered image".format(reg_img_path)) if not get_sitk: reg_img = sitk.GetArrayFromImage(reg_img) return (reg_img, reg_img_path) if return_path else reg_img
def load_registered_img( img_path: str, reg_name: str, get_sitk: bool = False, return_path: bool = False ) -> Union[Union[np.ndarray, sitk.Image], Tuple[Union[np.ndarray, sitk.Image], str]]: """Load atlas-based image that has been registered to another image. Args: img_path: Path as had been given to generate the registered images, with the parent path of the registered images and base name of the original image. reg_name: Atlas image suffix to open. Can be an absolute path, which will be used directly, ignoring ``img_path``. get_sitk: True if the image should be returned as a SimpleITK image; defaults to False, in which case the corresponding Numpy array will be extracted instead. return_path: True to return the path from which the image was loaded; defaults to False. Returns: The atlas-based image as a Numpy array, or a :class:`sitk.Image` object if ``get_sitk`` is True. Also returns the loaded path if ``return_path`` is True. Raises: ``FileNotFoundError`` if the path cannot be found. """ reg_img_path = reg_name if not os.path.isabs(reg_name): # use suffix given as an absolute path directly; otherwise, get # registered image extension matched to that of main image reg_img_path = reg_out_path(img_path, reg_name, True) reg_img, reg_img_path = read_sitk(reg_img_path) if reg_img is None: # fallback to loading barren reg_name from img_path's dir reg_img_path = os.path.join(os.path.dirname(img_path), libmag.match_ext(img_path, reg_name)) reg_img, reg_img_path = read_sitk(reg_img_path) if reg_img is None: raise FileNotFoundError( "could not find registered image from {} and {}".format( img_path, os.path.splitext(reg_name)[0])) if not get_sitk: reg_img = sitk.GetArrayFromImage(reg_img) return (reg_img, reg_img_path) if return_path else reg_img
def write_reg_images(imgs_write, prefix, copy_to_suffix=False, ext=None, prefix_is_dir=False): """Write registered images to file. Args: imgs_write: Dictionary of ``{suffix: image}``, where ``suffix`` is a registered images suffix, such as :const:``IMAGE_LABELS``, and ``image`` is a SimpleITK image object. If the image does not exist, the file will not be written. prefix: Base path from which to construct registered file paths. Parent directories will be created if necessary. copy_to_suffix: If True, copy the output path to a file in the same directory with ``suffix`` as the filename, which may be useful when setting the registered images as the main images in the directory. Defaults to False. ext: Replace extension with this value if given; defaults to None. prefix_is_dir (bool): True to treat ``prefix`` as a directory; defaults to False to get the directory name of ``prefix``. """ # get parent directories and create them if necessary target_dir = prefix if prefix_is_dir else os.path.dirname(prefix) if len(target_dir) > 0 and not os.path.exists(target_dir): os.makedirs(target_dir) for suffix in imgs_write.keys(): # write a registered image file for each entry img = imgs_write[suffix] if img is None: continue if ext: suffix = libmag.match_ext(ext, suffix) out_path = reg_out_path(prefix, suffix) sitk.WriteImage(img, out_path, False) print("wrote registered image to", out_path) if copy_to_suffix: # copy metadata file to allow opening images from bare suffix name, # such as when this atlas becomes the new atlas for registration out_path_copy = os.path.join(target_dir, suffix) shutil.copy(out_path, out_path_copy) print("also copied to", out_path_copy)
def reg_out_path(file_path, reg_name, match_ext=False): """Generate a path for a file registered to another file. Args: file_path: Full path of file registered to. :attr:`config.series` will be appended unless ``file_path`` is a directory. reg_name: Suffix for type of registration, eg :const:``IMG_LABELS``. match_ext: True to change the extension of ``reg_name`` to match that of ``file_path``. Returns: str: Full path with the registered filename including appropriate extension at the end. """ if match_ext: reg_name = libmag.match_ext(file_path, reg_name) if os.path.isdir(file_path): return os.path.join(file_path, reg_name) else: file_path_base = importer.filename_to_base(file_path, config.series) return file_path_base + "_" + reg_name