wsireg.utils package
Submodules
wsireg.utils.config_utils module
wsireg.utils.im_utils module
- class wsireg.utils.im_utils.CziRegImageReader(arg, multifile=True, filesize=None, detectmosaic=True)[source]
Bases:
CziFile
Sub-class of CziFile with added functionality to only read certain channels
- sub_asarray(resize=True, order=0, out=None, max_workers=None, channel_idx=None, as_uint8=False)[source]
Return image data from file(s) as numpy array.
- Parameters:
resize (bool) – If True (default), resize sub/supersampled subblock data.
order (int) – The order of spline interpolation used to resize sub/supersampled subblock data. Default is 0 (nearest neighbor).
out (np.ndarray) – Buffer where image data will be saved. If numpy.ndarray, a writable array of compatible dtype and shape. If str or open file, the file name or file object used to create a memory-map to an array stored in a binary file on disk.
max_workers (int) – Maximum number of threads to read and decode subblock data. By default up to half the CPU cores are used.
channel_idx (int or list of int) – The indices of the channels to extract
as_uint8 (bool) – byte-scale image data to np.uint8 data type
out – image read with selected parameters as np.ndarray
- sub_asarray_rgb(resize=True, order=0, out=None, max_workers=None, channel_idx=None, as_uint8=False, greyscale=False)[source]
Return image data from file(s) as numpy array.
- Parameters:
resize (bool) – If True (default), resize sub/supersampled subblock data.
order (int) – The order of spline interpolation used to resize sub/supersampled subblock data. Default is 0 (nearest neighbor).
out (np.ndarray) – Buffer where image data will be saved. If numpy.ndarray, a writable array of compatible dtype and shape. If str or open file, the file name or file object used to create a memory-map to an array stored in a binary file on disk.
max_workers (int) – Maximum number of threads to read and decode subblock data. By default up to half the CPU cores are used.
channel_idx (int or list of int) – The indices of the channels to extract
as_uint8 (bool) – byte-scale image data to np.uint8 data type
out – image read with selected parameters as np.ndarray
- wsireg.utils.im_utils.add_ome_axes_single_plane(image_np)[source]
Reshapes np.ndarray image to match OME-zarr standard
- Parameters:
image_np (np.ndarray) – image to which additional axes are added to meet OME-zarr standard
- Returns:
image_np – reshaped image array
- Return type:
np.ndarray
- wsireg.utils.im_utils.calc_pyramid_levels(xy_final_shape, tile_size)[source]
Calculate number of pyramids for a given image dimension and tile size Stops when further downsampling would be smaller than tile_size.
- Parameters:
xy_final_shape (np.ndarray) – final shape in xy order
tile_size (int) – size of the tiles in the pyramidal layers
- Returns:
res_shapes – list of tuples of the shapes of the downsampled images
- Return type:
list
- wsireg.utils.im_utils.czi_tile_grayscale(rgb_image)[source]
convert RGB image data to greyscale
- Parameters:
rgb_image (np.ndarray) – image data
- Returns:
image – returns 8-bit greyscale image for 24-bit RGB image
- Return type:
np.ndarray
- wsireg.utils.im_utils.format_channel_names(channel_names, n_ch)[source]
Format channel names and ensure number of channel names matches number of channels or default to C1, C2, C3, etc.
- Parameters:
channel_names (list) – list of str that are channel names
n_ch (int) – number of channels detected in image
- Returns:
list of str that are formatted
- Return type:
channel_names
- wsireg.utils.im_utils.generate_channels(channel_names, channel_colors, im_dtype)[source]
Generate OME-zarr channels metadata
- Parameters:
channel_names (list) –
channel_colors (list) –
im_dtype (np.dtype) –
- Returns:
channel_info – list of dicts containing OME-zarr channel info
- Return type:
list
- wsireg.utils.im_utils.get_final_tform_info(final_transform)[source]
Extract size and spacing information from wsireg’s final transformation elastix data
- Parameters:
final_transform (itk.Transform) – itk.Transform with added attributes containing transform data
- Returns:
y_size (int)
x_size (int)
y_spacing (float)
x_spacing (float)
- wsireg.utils.im_utils.get_pyramid_info(y_size, x_size, n_ch, tile_size)[source]
Get pyramidal info for OME-zarr output
- Parameters:
y_size (int) – y dimension of base layer
x_size (int) – x dimension of base layer
n_ch (int) – number of channels in the image
tile_size (int) – tile size of the image
- Returns:
pyr_levels – pyramidal levels
pyr_shapes – OME-zarr pyramid shapes for all levels
- wsireg.utils.im_utils.get_sitk_image_info(image_filepath)[source]
Get image info for files only ready by SimpleITK
- Parameters:
image_filepath (str) – filepath to image
- Returns:
im_dims (np.ndarray) – image dimensions in np.ndarray
im_dtype (np.dtype) – data type of the image
- wsireg.utils.im_utils.get_tifffile_info(image_filepath: str | Path) Tuple[Tuple[int, int, int], dtype, int] [source]
- wsireg.utils.im_utils.grayscale(rgb_image, is_interleaved=False)[source]
convert RGB image data to greyscale
- Parameters:
rgb_image (np.ndarray) – image data
- Returns:
image – returns 8-bit greyscale image for 24-bit RGB image
- Return type:
np.ndarray
- wsireg.utils.im_utils.guess_rgb(shape)[source]
Guess if the passed shape comes from rgb data. If last dim is 3 or 4 assume the data is rgb, including rgba.
- Parameters:
shape (list of int) – Shape of the data that should be checked.
- Returns:
If data is rgb or not.
- Return type:
bool
- wsireg.utils.im_utils.image_to_zarr_store(zgrp, image, channel_idx, n_pyr_levels, pyr_levels)[source]
Write image into zarr store with sub resolutions
- Parameters:
grp (zarr.store) – initialized store
image (sitk.Image) – image
channel_idx (int) – which channel the image represents
n_pyr_levels (int) –
pyr_levels (list) –
- wsireg.utils.im_utils.prepare_ome_xml_str(y_size, x_size, n_ch, im_dtype, is_rgb, **ome_metadata)[source]
- wsireg.utils.im_utils.prepare_ome_zarr_group(zarr_store_dir, y_size, x_size, n_ch, im_dtype, tile_size=512, channel_names=None, channel_colors=None)[source]
Prepare OME-zarr store with all meta data and channel info and initialize store
- Parameters:
zarr_store_dir (str) – filepath to zarr store
y_size (int) – y dimension of base layer
x_size (int) – x dimension of base layer
n_ch (int) – number of channels in the image
im_dtype (np.dtype) – data type of the image
tile_size (int) – tile size of the image
channel_names (list) – list of str channel names
channel_colors – list of hex or str channel colors
- Returns:
grp (zarr.store) – initialized store
n_pyr_levels (int) – number of sub-resolutions
pyr_levels (list) – shapes of sub-resolutions
- wsireg.utils.im_utils.preprocess_dask_array(array: Array, preprocessing: ImagePreproParams | None = None)[source]
- wsireg.utils.im_utils.read_preprocess_array(array, preprocessing, force_rgb=None)[source]
Read np.array, zarr.Array, or dask.array image into memory with preprocessing for registration.
- wsireg.utils.im_utils.sitk_backend(image_filepath, preprocessing)[source]
Read image with SimpleITK..this will always read the full image into memory
- Parameters:
image_filepath (str) – path to the image file
preprocessing – whether to do some read-time pre-processing - greyscale conversion (at the tile level) - read individual or range of channels (at the tile level)
- Returns:
image – image ready for other registration pre-processing
- Return type:
sitk.Image
- wsireg.utils.im_utils.sitk_inv_int(image)[source]
inverts intensity of images for registration, useful for alignment of brightfield and fluorescence images :param image: SimpleITK image s
- Return type:
Intensity inverted SimpleITK image
- wsireg.utils.im_utils.sitk_max_int_proj(image: Image) Image [source]
Finds maximum intensity projection of multi-channel SimpleITK image
- Parameters:
image – multichannel impleITK image
- Return type:
SimpleITK image
- wsireg.utils.im_utils.sitk_vect_to_gs(image)[source]
converts simpleITK RGB image to greyscale using cv2 :param image: SimpleITK image
- Return type:
Greyscale SimpleITK image
- wsireg.utils.im_utils.std_prepro()[source]
Catch all dictionary of preprocessing functions that will result in a single 2D image for registration :rtype: dictionary of processing parameters
- wsireg.utils.im_utils.tf_get_largest_series(image_filepath: str | Path) int [source]
Determine largest series for .scn files by examining metadata For other multi-series files, find the one with the most pixels
- Parameters:
image_filepath (str) – path to the image file
- Returns:
largest_series – index of the largest series in the image data
- Return type:
int
- wsireg.utils.im_utils.tf_zarr_read_single_ch(image_filepath, channel_idx, is_rgb, is_rgb_interleaved=True)[source]
Reads a single channel using zarr or dask in combination with tifffile
- Parameters:
image_filepath (str) – file path to image
channel_idx (int) – index of the channel to be read
is_rgb (bool) – whether image is rgb interleaved
- Returns:
im – image as a np.ndarray
- Return type:
np.ndarray
- wsireg.utils.im_utils.tifffile_dask_backend(image_filepath, largest_series, preprocessing, force_rgb=None)[source]
Read image with tifffile and use dask to read data into memory
- Parameters:
image_filepath (str) – path to the image file
largest_series (int) – index of the largest series in the image
preprocessing – whether to do some read-time pre-processing - greyscale conversion (at the tile level) - read individual or range of channels (at the tile level)
- Returns:
image – image ready for other registration pre-processing
- Return type:
sitk.Image
- wsireg.utils.im_utils.tifffile_to_dask(im_fp: str | ~pathlib.Path, largest_series: int, level=<class 'int'>) Array | List[Array] [source]
- wsireg.utils.im_utils.tifffile_zarr_backend(image_filepath, largest_series, preprocessing, force_rgb=None)[source]
Read image with tifffile and use zarr to read data into memory
- Parameters:
image_filepath (str) – path to the image file
largest_series (int) – index of the largest series in the image
preprocessing – whether to do some read-time pre-processing - greyscale conversion (at the tile level) - read individual or range of channels (at the tile level)
- Returns:
image – image ready for other registration pre-processing
- Return type:
sitk.Image
- wsireg.utils.im_utils.transform_to_ome_tiff(tform_reg_im, image_name, output_dir, final_transform, composite_transform, tile_size=512, write_pyramid=True)[source]
wsireg.utils.itk_im_conversions module
wsireg.utils.reg_utils module
- wsireg.utils.reg_utils.json_to_pmap_dict(json_file)[source]
Load python dict of SimpleElastix stored in json
- Parameters:
json_file (dict) – filepath to json contained SimpleElastix parameter map
- wsireg.utils.reg_utils.parameter_to_itk_pobj(reg_param_map)[source]
Transfer parameter data stored in dict to ITKElastix ParameterObject
- Parameters:
reg_param_map (dict) – elastix registration parameters
- Returns:
itk_param_map – ITKElastix object for registration parameters
- Return type:
itk.ParameterObject
- wsireg.utils.reg_utils.pmap_dict_to_json(pmap_dict, output_file)[source]
Save python dict of ITKElastix to json
- Parameters:
pmap_dict (dict) – parameter map stored in python dict
output_file (str) – filepath of where to save the json
- wsireg.utils.reg_utils.pmap_dict_to_sitk(pmap_dict)[source]
Convert python dict to SimpleElastix ParameterMap
- Parameters:
pmap_dict – SimpleElastix ParameterMap in python dictionary
- Return type:
SimpleElastix ParameterMap of Python dict
- wsireg.utils.reg_utils.register_2d_images_itkelx(source_image, target_image, reg_params: List[Dict[str, List[str]]], reg_output_fp: str | Path, histogram_match=False, return_image=False)[source]
Register 2D images with multiple models and return a list of elastix transformation maps.
- Parameters:
source_image (SimpleITK.Image) – RegImage of image to be aligned
target_image (SimpleITK.Image) – RegImage that is being aligned to (grammar is hard)
reg_params (list of dict) – registration parameter maps stored in a dict, can be file paths to SimpleElastix parameterMaps stored as text or one of the default parameter maps (see parameter_load() function)
reg_output_fp (str) – where to store registration outputs (iteration data and transformation files)
histogram_match (bool) – whether to attempt histogram matching to improve registration
- Returns:
tform_list (list) – list of ITKElastix transformation parameter maps
image (itk.Image) – resulting registered moving image
wsireg.utils.shape_utils module
- wsireg.utils.shape_utils.approx_polygon_contour(mask: ndarray, percent_arc_length=0.01)[source]
Approximate binary mask contours to polygon vertices using cv2.
- Parameters:
mask (numpy.ndarray) – 2-d numpy array of datatype np.uint8.
percent_arc_length (float) – scaling of epsilon for polygon approximate vertices accuracy. maximum distance of new vertices from original.
- Returns:
returns an 2d array of vertices, rows: points, columns: y,x
- Return type:
numpy.ndarray
- wsireg.utils.shape_utils.get_int_dtype(value: int)[source]
Determine appropriate bit precision for indexed image
- Parameters:
value (int) – number of shapes
- Returns:
dtype – apppropriate data type for index mask
- Return type:
np.dtype
- wsireg.utils.shape_utils.gj_to_np(gj: dict)[source]
Convert geojson representation to np.ndarray representation of shape
- Parameters:
gj (dict) – GeoJSON data stored as python dict
- Returns:
- containing keys
”array”: np.ndarray - x,y point data in array “shape_type”: str - indicates GeoJSON shape_type (Polygon, MultiPolygon, etc.) “shape_name”: str - name inherited from QuPath GeoJSON
- Return type:
dict
- wsireg.utils.shape_utils.index_mask_to_shapes(index_mask, shape_name, tf_shapes)[source]
Find the polygons of a transformed shape mask, conveting binary mask to list of polygon verteces and sorting by numerical index
- Parameters:
index_mask (np.ndarray) – mask where each shape is defined by it’s index
shape_name (str) – name of the shape
tf_shapes (list) – original list of shape GeoJSON data to be updated
- Returns:
updated_shapes – dict of GeoJSON information with updated coordinate information
- Return type:
list
- wsireg.utils.shape_utils.insert_transformed_pts_gj(gj_data: list, np_data: list)[source]
insert point data into a list of geojson data
- Parameters:
shape_gj (dict) – dict of GeoJSON information
shape_np (dict) – transformed point data in wsireg shape dict
- Returns:
shape_gj – dict of GeoJSON information with updated coordinate information
- Return type:
dict
- wsireg.utils.shape_utils.invert_nonrigid_transforms(itk_transforms: list)[source]
Check list of sequential ITK transforms for non-linear (i.e., bspline) transforms Transformations need to be inverted to transform from moving to fixed space as transformations are mapped from fixed space to moving. This will first convert any non-linear transforms to a displacement field then invert the displacement field using ITK methods. It usually works quite well but is not an exact solution. Linear transforms can be inverted on the fly when transforming points
- Parameters:
itk_transforms (list) – list of itk.Transform
- Returns:
itk_transforms – list of itk.Transform where any non-linear transforms are replaced with an inverted displacement field
- Return type:
list
- wsireg.utils.shape_utils.itk_transform_pts(pt_data: ndarray, itk_transforms: list, px_idx=True, source_res=1, output_idx=True, target_res=2)[source]
Transforms x,y points stored in np.ndarray using list of ITK transforms All transforms are in physical coordinates, so all points must be converted to physical coordinates before transformation, but this function allows converting back to pixel indices after transformation
Can intake points in physical coordinates is px_idx == False Can output points in physical coordinates if output_idx == False
- Parameters:
pt_data (np.ndarray) – array where rows are points and columns are x,y
itk_transforms (list) – list of ITK transforms, non-linear transforms should be inverted
px_idx (bool) – whether points are specified in physical coordinates (i.e., microns) or in pixel indices
source_res (float) – resolution of the image on which annotations were made
output_idx (bool) – whether transformed points should be output in physical coordinates (i.e., microns) or in pixel indices
target_res (float) – resolution of the final target image for conversion back to pixel indices
- Returns:
tformed_pts – transformed points array where rows are points and columns are x,y
- Return type:
np.ndarray
- wsireg.utils.shape_utils.np_to_geojson(np_array: ndarray, shape_type='polygon', shape_name='unnamed')[source]
convert np.ndarray to GeoJSON dict
- Parameters:
np_array (np.ndarray) – coordinates of data
shape_type (str) – GeoJSON shape type
shape_name (str) – Name of the shape
- Returns:
shape_gj (dict) – dict of GeoJSON information
shape_np (dict) –
- dict of GeoJSON information stored in np.ndarray
”array”: np.ndarray - x,y point data in array “shape_type”: str - indicates GeoJSON shape_type (Polygon, MultiPolygon, etc.) “shape_name”: str - name inherited from QuPath GeoJSON
- wsireg.utils.shape_utils.prepare_pt_transformation_data(transformations, compute_inverse=True)[source]
Read and prepare wsireg transformation data for point set transformation
- Parameters:
transformations – list of dict containing elastix transformation data or str to wsireg .json file containing elastix transformation data
compute_inverse (bool) – whether or not to compute the inverse transformation for moving to fixed point transformations
- Returns:
itk_pt_transforms (list) – list of transformation data ready to operate on points
target_res – physical spacing of the final transformation in the transform sequence This is needed to map coordinates defined as pixel indices to physical coordinates and then back
- wsireg.utils.shape_utils.read_geojson(json_file: str)[source]
Read GeoJSON files (and some QuPath metadata).
- Parameters:
json_file (str) – file path of QuPath exported GeoJSON
- Returns:
gj_data (dict) – dict of GeoJSON information
shapes_np (dict) –
- dict of GeoJSON information stored in np.ndarray
”array”: np.ndarray - x,y point data in array “shape_type”: str - indicates GeoJSON shape_type (Polygon, MultiPolygon, etc.) “shape_name”: str - name inherited from QuPath GeoJSON
- wsireg.utils.shape_utils.scale_shape_coordinates(poly: dict, scale_factor: float)[source]
Scale coordinates by a factor
- Parameters:
poly (dict) – dict of coordinate data contain np.ndarray in “array” key
scale_factor (float) – isotropic scaling factor for the coordinates
- Returns:
poly – dict containing coordinates scaled by scale_factor
- Return type:
dict
- wsireg.utils.shape_utils.shape_reader(shape_data, **kwargs)[source]
Read shape data for transformation Shape data is stored as numpy arrays for operations but also as GeoJSON to contain metadata and interface with QuPath
- Parameters:
shape_data (list of np.ndarray or str) – if str, will read data as GeoJSON file, if np.ndarray with assume it is coordinates
kwargs – keyword args passed to np_to_geojson convert
- Returns:
shapes_gj (list of dicts) – list of dicts of GeoJSON information
shapes_np (list of dicts) – list of dicts of GeoJSON information stored in np.ndarray “array”: np.ndarray - x,y point data in array “shape_type”: str - indicates GeoJSON shape_type (Polygon, MultiPolygon, etc.) “shape_name”: str - name inherited from QuPath GeoJSON
- wsireg.utils.shape_utils.transform_shapes(shape_data: list, itk_transforms: list, px_idx=True, source_res=1, output_idx=True, target_res=2)[source]
Convenience function to apply itk_transform_pts to a list of shape data
- Parameters:
shape_data – list of arrays where rows are points and columns are x,y
itk_transforms (list) – list of ITK transforms, non-linear transforms should be inverted
px_idx (bool) – whether points are specified in physical coordinates (i.e., microns) or in pixel indices
source_res (float) – resolution of the image on which annotations were made
output_idx (bool) – whether transformed points should be output in physical coordinates (i.e., microns) or in pixel indices
target_res (float) – resolution of the final target image for conversion back to pixel indices
- Returns:
transformed_shape_data – list of transformed np.ndarray data where rows are points and columns are x,y
- Return type:
list
wsireg.utils.tform_conversion module
wsireg.utils.tform_utils module
- wsireg.utils.tform_utils.apply_transform_dict_itkelx(image_fp, image_res, tform_dict_in, prepro_dict=None, is_shape_mask=False, writer='sitk', **im_tform_kwargs)[source]
Apply a complex series of transformations in a python dictionary to an image
- Parameters:
image_fp (str) – file path to the image to be transformed, it will be read in it’s entirety
image_res (float) – pixel resolution of image to be transformed
tform_dict (dict of lists) – dict of SimpleElastix transformations stored in lists, may contain an “initial” transforms (preprocessing transforms) these will be applied first, then the key order of the dict will determine the rest of the transformations
is_shape_mask (bool) – whether the image being transformed is a shape mask (determines import)
- Returns:
image – image that has been transformed
- Return type:
itk.Image
- wsireg.utils.tform_utils.compute_rot_bound(image, angle=30)[source]
compute the bounds of an image after by an angle
- Parameters:
image (sitk.Image) – SimpleITK image that will be rotated angle
angle (float) – angle of rotation in degrees, rotates counter-clockwise if positive
- Return type:
tuple of the rotated image’s size in x and y
- wsireg.utils.tform_utils.gen_aff_tform_flip(image, spacing, flip='h')[source]
generate a SimpleElastix transformation parameter Map to horizontally or vertically flip image
- Parameters:
image (sitk.Image) – SimpleITK image that will be rotated
spacing (float) – Physical spacing of the SimpleITK image
flip (str) – “h” or “v” for horizontal or vertical flipping, respectively
- Return type:
SimpleITK.ParameterMap of flipping transformation (AffineTransform)
- wsireg.utils.tform_utils.gen_rigid_tform_rot(image, spacing, angle)[source]
generate a SimpleElastix transformation parameter Map to rotate image by angle :param image: SimpleITK image that will be rotated :type image: sitk.Image :param spacing: Physical spacing of the SimpleITK image :type spacing: float :param angle: angle of rotation in degrees, rotates counter-clockwise if positive :type angle: float
- Return type:
SimpleITK.ParameterMap of rotation transformation (EulerTransform)
- wsireg.utils.tform_utils.gen_rigid_translation(image, spacing, translation_x, translation_y, size_x, size_y)[source]
generate a SimpleElastix transformation parameter Map to rotate image by angle :param image: SimpleITK image that will be rotated :type image: sitk.Image :param spacing: Physical spacing of the SimpleITK image :type spacing: float
- Return type:
SimpleITK.ParameterMap of rotation transformation (EulerTransform)
- wsireg.utils.tform_utils.identity_elx_transform(image_size: Tuple[int, int], image_spacing: Tuple[int, int] | Tuple[float, float])[source]
- wsireg.utils.tform_utils.transform_2d_image_itkelx(image, transformation_maps, writer='sitk', **zarr_kwargs)[source]
Transform 2D images with multiple models and return the transformed image or write the transformed image to disk as a .tif file. Multichannel or multicomponent images (RGB) have to be transformed a single channel at a time This function takes care of performing those transformations and reconstructing the image in the same data type as the input :param image: Image to be transformed :type image: SimpleITK.Image :param transformation_maps: list of SimpleElastix ParameterMaps to used for transformation :type transformation_maps: list
- Return type:
Transformed SimpleITK.Image