API

Normalisation and Augmentation

exception beast.reinhard.ArrayTypeExcpeiton(message='Numpy array is not of type UInt8.')

Bases: Exception

Raised when a numpy array is not of type UInt8.

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class beast.reinhard.ReinhardTileNormaliser(file_loader: ~typing.Callable = <function read_tile>, logfile=None, terminal_log_level=10, file_log_level=10)

Bases: BaseNormaliser

Class to transform the colour profile of an image tile to match a target using the Reinhard Colour Transfer Algorithm (https://www.cs.tau.ac.il/~turkel/imagepapers/ColorTransfer.pdf).

Normalisation is performed by computing the mean and standard deviation of the channels in LAB colour space for the source and target images. The mean and standard deviation of the source image is then scaled to match the target image.

Args:

file_loader (Callable, optional): The function to load the tile. Defaults to read_tile. A function that accepts a path and returns a numpy array can be supplied by the user for custom loading. logfile (str, optional): The path to the log file. Defaults to None. terminal_log_level (int, optional): The level of logging to the terminal. Defaults to logging.DEBUG. file_log_level (int, optional): The level of logging to the file. Defaults to logging.DEBUG.

fit(path_or_array) None

Function to fit the normalisation to a target whole slide image.

Args:

path_or_array <str, Path, np.ndarray>: Path to the whole slide image to fit to, or the array to fit to.

load_fit(path: Path) None

Function to load the target normalisation metadata from a JSON file.

Args:

path <str, Path>: Path to load the JSON file from.

normalise(path_or_array) ndarray

Function to normalise a whole slide image using the specified normalisation type.

Args:

path_or_array <str, Path, np.ndarray>: Path to the whole slide image to normalise, or the array to normalise.

Returns:

np.ndarray: Normalised array.

save_fit(path: Path) None

Function to save the target normalisation metadata to a JSON file.

Args:

path <str, Path>: Path to save the JSON file to.

class beast.reinhard.ReinhardWSINormaliser(file_loader: ~typing.Callable = <function read_wsi>, logfile=None, terminal_log_level=10, file_log_level=10, num_threads: int = 16)

Bases: BaseNormaliser

Class to transform the colour profile of a whole slide image to match a target using the Reinhard Colour Transfer Algorithm (https://www.cs.tau.ac.il/~turkel/imagepapers/ColorTransfer.pdf). Warning: This class considers the colour profile of the entire slide when normalising, this is useful for visualisation of the slide but may not be appropriate for analysis when stain intensity can vary across the slide. For analysis, use the ReinhardTileNormaliser or ReinhardWSITesselatedNormaliser class.

Normalistion is carried out by standardising the luminosity of the source image, then calculating the mean and standard deviation of the channels in the LAB colour space. These channels are then scaled across the whole slide to match a target colour profile.

Args:

file_loader (Callable, optional): The function to use to load the file. Defaults to read_wsi. A function that accepts a path and returns a numpy array can be supplied for custom loading. logfile (str, optional): The path to the log file. Defaults to None. terminal_log_level (int, optional): The log level for the terminal. Defaults to logging.DEBUG. file_log_level (int, optional): The log level for the log file. Defaults to logging.DEBUG. num_threads (int, optional): The number of threads to use. Defaults to 16.

Raises:

ArrayTypeExcpeiton: Raised when a numpy array is not of type UInt8.

fit(path_or_array) None

Function to fit the normalisation to a target whole slide image.

Args:

path_or_array <str, Path, np.ndarray>: Path to the whole slide image to fit to, or the array to fit to.

load_fit(path: Path) None

Function to load the target normalisation metadata from a JSON file.

Args:

path <str, Path>: Path to load the JSON file from.

normalise(path_or_array) ndarray

Function to normalise a whole slide image using the specified normalisation type.

Args:

path_or_array <str, Path, np.ndarray>: Path to the whole slide image to normalise, or the array to normalise.

Returns:

np.ndarray: Normalised array.

save_fit(path: Path) None

Function to save the target normalisation metadata to a JSON file.

Args:

path <str, Path>: Path to save the JSON file to.

class beast.macenko.MacenkoStainAugmenter(sigma1=0.5, sigma2=0.05, file_loader: ~typing.Callable = <function read_tile>, logfile=None, terminal_log_level=10, file_log_level=10)

Bases: BaseDeconStainAugmenter

Class to augment the stain profile and intensity of a tile through Macenko stain vector estimation (https://www.cs.unc.edu/~mn/sites/default/files/macenko2009.pdf) and subsequent intensity or compoment matrix perturbation.

Args:

sigma1 (float): The standard deviation of the Gaussian blur applied to the background. sigma2 (float): The standard deviation of the Gaussian blur applied to the foreground. file_loader (Callable, optional): The function to use to load the tile. Defaults to read_tile. A function that accepts a path and returns a numpy array can be supplied to allow for custom loading. logfile (Path, optional): The path to save the log file to. Defaults to None. terminal_log_level (int, optional): The log level to print to the terminal. Defaults to logging.DEBUG. file_log_level (int, optional): The log level to print to the log file. Defaults to logging.DEBUG.

augment_colour(tile_arr: ndarray, stain_to_augment: int = -1) ndarray

Augments the tile stain colour profile.

Args:

tile_arr (np.ndarray): The tile array.

Returns:

np.ndarray: The converted tile array.

augment_intensity(tile_arr: ndarray, stain_to_augment: int = -1) ndarray

Augments the tile stain intensity.

Args:

tile_arr (np.ndarray): The tile array. stain_to_augment (int): (-1,0,1) The stain to augment. If -1, all stains are augmented.

Returns:

np.ndarray: The converted tile array.

fit(tile_arr: ndarray) Tuple[dict, ndarray]

Retrieves the stain components for the given tile.

Args:

tile_arr (np.ndarray): The tile array.

Returns:

dict: The stain matrix.

load_fit(json_pth: Path) None

Loads the target stain metadata from a json file.

Args:

json_pth (Path): The path to load the json file from.

Returns:

dict: The target stain metadata.

save_fit(json_pth: Path) None

Saves the target stain metadata to a json file.

Args:

json_pth (Path): The path to save the json file to.

Returns:

None

class beast.macenko.MacenkoTileNormaliser(intensity_sampling_method=IntensitySamplingMethod.PERCENTILE, intensity_percentile: float = 95.0, file_loader: ~typing.Callable = <function read_tile>, logfile=None, terminal_log_level=10, file_log_level=10)

Bases: BaseDeconTileNormaliser

Class to transform the stain profle and intensity in a tile to match a target using the Macenko stain vector estimation and normalisation algorithm (https://www.cs.unc.edu/~mn/sites/default/files/macenko2009.pdf).

Args:

intensity_sampling_method (IntensitySamplingMethod, optional): The method to use to sample the intensity of the image. Defaults to IntensitySamplingMethod.PERCENTILE. stain_percentile (float, optional): The percentile to use to sample the intensity of the image. Defaults to 95.0. file_loader (Callable, optional): The function to use to load the image. Defaults to read_tile. A function that accepts a path and returns a numpy array can be supplied to allow for custom loading. logfile (Path, optional): The path to save the log file to. Defaults to None. terminal_log_level (int, optional): The log level to print to the terminal. Defaults to logging.DEBUG. file_log_level (int, optional): The log level to print to the log file. Defaults to logging.DEBUG.

convert_to_stain1(tile_arr: ndarray, use_source: bool = False) ndarray

Converts the tile to only display stain one in RGB.

Args:

tile_arr (np.ndarray): The tile array. use_source (bool): Whether to use the source stain matrix or the target stain matrix to render stain 1.

Returns:

np.ndarray: The converted tile array.

convert_to_stain2(tile_arr: ndarray, use_source: bool = False) ndarray

Converts the tile to only display stain two in RGB.

Args:

tile_arr (np.ndarray): The tile array. use_source (bool): Whether to use the source stain matrix or the target stain matrix to render stain 2.

Returns:

np.ndarray: The converted tile array.

convert_to_stain_concentrations(tile_arr: ndarray, normalise_to_target_intensities=True) ndarray

Converts the tile to a two channel array of stain concentrations.

Args:

tile_arr (np.ndarray): The tile array.

Returns:

np.ndarray: The converted tile array.

fit(path_or_array) None

Function to fit the normalisation to a target whole slide image.

Args:

path_or_array <str, Path, np.ndarray>: Path to the whole slide image to fit to, or the array to fit to.

load_fit(json_pth: Path) None

Loads the target stain metadata from a json file.

Args:

json_pth (Path): The path to load the json file from.

Returns:

dict: The target stain metadata.

normalise(path_or_array) ndarray

Function to normalise a whole slide image using the specified normalisation type.

Args:

path_or_array <str, Path, np.ndarray>: Path to the whole slide image to normalise, or the array to normalise.

Returns:

np.ndarray: Normalised array.

save_fit(json_pth: Path) None

Saves the target stain metadata to a json file.

Args:

json_pth (Path): The path to save the json file to.

Returns:

None

class beast.macenko.MacenkoWSINormaliser(num_threads: int = 16, intensity_sampling_method=IntensitySamplingMethod.PERCENTILE, intensity_percentile: float = 95.0, no_pixel_samples: int = 2000000, file_loader: ~typing.Callable = <function read_wsi>, logfile=None, terminal_log_level=10, file_log_level=10)

Bases: BaseDeconWSINormaliser

Class to transform the stain profile and intensity in a whole slide image to match a target using the Macenko stain vector estimation and normalisation algorithm (https://www.cs.unc.edu/~mn/sites/default/files/macenko2009.pdf). Warning: This class considers the entire slide to have uniform staining, this is useful for visualisation but may not be appropriate for analysis when stain intensity varies across the slide. For analysis, use the MacenkoTileNormaliser or MacenkoWSITesselatedNormaliser class.

Args:

num_threads (int, optional): The number of threads to use. Defaults to 16. file_loader (Callable, optional): The function to use to load the image. Defaults to read_wsi. A function that accepts a path and returns a numpy array can be supplied to allow for custom loading. logfile (Path, optional): The path to save the log file to. Defaults to None. terminal_log_level (int, optional): The log level to print to the terminal. Defaults to logging.DEBUG. file_log_level (int, optional): The log level to print to the log file. Defaults to logging.DEBUG.

convert_to_stain1(slide_arr: ndarray, use_source: bool = False) ndarray

Converts the slide to only display stain 1 in RGB.

Args:

slide_arr (np.ndarray): The slide array. use_source (bool): Whether to use the source stain matrix or the target stain matrix to render stain 1.

Returns:

np.ndarray: The converted slide array.

convert_to_stain2(slide_arr: ndarray, use_source: bool = False) ndarray

Converts the slide to only display stain two in RGB.

Args:

slide_arr (np.ndarray): The slide array. use_source (bool): Whether to use the source stain matrix or the target stain matrix to render stain 2.

Returns:

np.ndarray: The converted slide array.

convert_to_stain_concentrations(slide_arr: ndarray) ndarray

Converts the slide to a two channel array of stain concentrations.

Args:

slide_arr (np.ndarray): The slide array.

Returns:

np.ndarray: The converted slide array.

fit(path_or_array) None

Function to fit the normalisation to a target whole slide image.

Args:

path_or_array <str, Path, np.ndarray>: Path to the whole slide image to fit to, or the array to fit to.

load_fit(json_pth: Path) None

Loads the target stain metadata from a json file.

Args:

json_pth (Path): The path to load the json file from.

Returns:

dict: The target stain metadata.

normalise(path_or_array) ndarray

Function to normalise a whole slide image using the specified normalisation type.

Args:

path_or_array <str, Path, np.ndarray>: Path to the whole slide image to normalise, or the array to normalise.

Returns:

np.ndarray: Normalised array.

save_fit(json_pth: Path) None

Saves the target stain metadata to a json file.

Args:

json_pth (Path): The path to save the json file to.

Returns:

None

class beast.vahadane.VahadaneStainAugmenter(sigma1=0.4, sigma2=0.05, file_loader: ~typing.Callable = <function read_tile>, logger: ~logging.Logger | None = None)

Bases: BaseDeconStainAugmenter

Class to augment the tissue colour profile of a tile through the Vahadane NMF stain deconvolution algorithm (https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=7460968) and subsequent intensity or compoment matrix perturbation.

Args:

sigma1 (float): The standard deviation of the Gaussian blur applied to the background. sigma2 (float): The standard deviation of the Gaussian blur applied to the foreground. file_loader (Callable): The function to use to load the tile. logger (logging.Logger, optional): The logger to use. Defaults to None.

augment_colour(tile_arr: ndarray, stain_to_augment: int = -1) ndarray

Augments the tile stain colour profile.

Args:

tile_arr (np.ndarray): The tile array.

Returns:

np.ndarray: The converted tile array.

augment_intensity(tile_arr: ndarray, stain_to_augment: int = -1) ndarray

Augments the tile stain intensity.

Args:

tile_arr (np.ndarray): The tile array. stain_to_augment (int): (-1,0,1) The stain to augment. If -1, all stains are augmented.

Returns:

np.ndarray: The converted tile array.

fit(tile_arr: ndarray) Tuple[dict, ndarray]

Retrieves the stain components for the given tile.

Args:

tile_arr (np.ndarray): The tile array.

Returns:

dict: The stain matrix.

load_fit(json_pth: Path) None

Loads the target stain metadata from a json file.

Args:

json_pth (Path): The path to load the json file from.

Returns:

dict: The target stain metadata.

save_fit(json_pth: Path) None

Saves the target stain metadata to a json file.

Args:

json_pth (Path): The path to save the json file to.

Returns:

None

class beast.vahadane.VahadaneTileNormaliser(intensity_sampling_method=IntensitySamplingMethod.PERCENTILE, intensity_percentile: float = 95.0, file_loader: ~typing.Callable = <function read_tile>, logfile=None, terminal_log_level=10, file_log_level=10)

Bases: BaseDeconTileNormaliser

Class to transform the stain colour profile and intensity in a tile to match a target using the Vahadane NMF stain deconvolution algorithm (https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=7460968).

Args:

intensity_sampling_method (IntensitySamplingMethod, optional): The method to use to sample the intensity. Defaults to IntensitySamplingMethod.PERCENTILE. stain_percentile (float, optional): The maximum percentile of the stain intensity to use. Defaults to 90.0. file_loader (Callable, optional): The function to use to load the image. Defaults to read_tile. A function that accepts a path and returns a numpy array can be supplied to allow for custom loading. logfile (Path, optional): The path to save the log file to. Defaults to None. terminal_log_level (int, optional): The log level to print to the terminal. Defaults to logging.DEBUG. file_log_level (int, optional): The log level to print to the log file. Defaults to logging.DEBUG.

convert_to_stain1(tile_arr: ndarray, use_source: bool = False) ndarray

Converts the tile to only display stain one in RGB.

Args:

tile_arr (np.ndarray): The tile array. use_source (bool): Whether to use the source stain matrix or the target stain matrix to render stain 1.

Returns:

np.ndarray: The converted tile array.

convert_to_stain2(tile_arr: ndarray, use_source: bool = False) ndarray

Converts the tile to only display stain two in RGB.

Args:

tile_arr (np.ndarray): The tile array. use_source (bool): Whether to use the source stain matrix or the target stain matrix to render stain 2.

Returns:

np.ndarray: The converted tile array.

convert_to_stain_concentrations(tile_arr: ndarray, normalise_to_target_intensities=True) ndarray

Converts the tile to a two channel array of stain concentrations.

Args:

tile_arr (np.ndarray): The tile array.

Returns:

np.ndarray: The converted tile array.

fit(path_or_array) None

Function to fit the normalisation to a target whole slide image.

Args:

path_or_array <str, Path, np.ndarray>: Path to the whole slide image to fit to, or the array to fit to.

load_fit(json_pth: Path) None

Loads the target stain metadata from a json file.

Args:

json_pth (Path): The path to load the json file from.

Returns:

dict: The target stain metadata.

normalise(path_or_array) ndarray

Function to normalise a whole slide image using the specified normalisation type.

Args:

path_or_array <str, Path, np.ndarray>: Path to the whole slide image to normalise, or the array to normalise.

Returns:

np.ndarray: Normalised array.

save_fit(json_pth: Path) None

Saves the target stain metadata to a json file.

Args:

json_pth (Path): The path to save the json file to.

Returns:

None

class beast.vahadane.VahadaneWSINormaliser(num_threads: int = 16, intensity_sampling_method=IntensitySamplingMethod.PERCENTILE, intensity_percentile: float = 95.0, no_pixel_samples: int = 2000000, file_loader: ~typing.Callable = <function read_wsi>, logfile=None, terminal_log_level=10, file_log_level=10)

Bases: BaseDeconWSINormaliser

Class to transform the stain intensity in a whole slide image to match a target using the Vahadane NMF stain deconvolution algorithm (https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=7460968). Warning: This class considers the entire slide to have uniform staining, this is useful for visualisation but may not be appropriate for analysis when stain intensity varies across the slide. For analysis, use the VahadaneTileNormaliser or VahadaneWSITesselatedNormaliser class.

Args:

num_threads (int, optional): The number of threads to use. Defaults to 16. intensity_sampling_method (IntensitySamplingMethod, optional): The method to use to sample the intensity. Defaults to IntensitySamplingMethod.PERCENTILE. stain_percentile (float, optional): The maximum percentile of the stain intensity to use. Defaults to 90.0. no_pixel_samples (int, optional): The number of pixels to sample. Defaults to 2000000. file_loader (Callable, optional): The function to use to load the image. Defaults to read_wsi. A function that accepts a path and returns a numpy array can be supplied to allow for custom loading. logfile (Path, optional): The path to save the log file to. Defaults to None. terminal_log_level (int, optional): The log level to print to the terminal. Defaults to logging.DEBUG. file_log_level (int, optional): The log level to print to the log file. Defaults to logging.DEBUG.

convert_to_stain1(slide_arr: ndarray, use_source: bool = False) ndarray

Converts the slide to only display stain 1 in RGB.

Args:

slide_arr (np.ndarray): The slide array. use_source (bool): Whether to use the source stain matrix or the target stain matrix to render stain 1.

Returns:

np.ndarray: The converted slide array.

convert_to_stain2(slide_arr: ndarray, use_source: bool = False) ndarray

Converts the slide to only display stain two in RGB.

Args:

slide_arr (np.ndarray): The slide array. use_source (bool): Whether to use the source stain matrix or the target stain matrix to render stain 2.

Returns:

np.ndarray: The converted slide array.

convert_to_stain_concentrations(slide_arr: ndarray) ndarray

Converts the slide to a two channel array of stain concentrations.

Args:

slide_arr (np.ndarray): The slide array.

Returns:

np.ndarray: The converted slide array.

fit(path_or_array) None

Function to fit the normalisation to a target whole slide image.

Args:

path_or_array <str, Path, np.ndarray>: Path to the whole slide image to fit to, or the array to fit to.

load_fit(json_pth: Path) None

Loads the target stain metadata from a json file.

Args:

json_pth (Path): The path to load the json file from.

Returns:

dict: The target stain metadata.

normalise(path_or_array) ndarray

Function to normalise a whole slide image using the specified normalisation type.

Args:

path_or_array <str, Path, np.ndarray>: Path to the whole slide image to normalise, or the array to normalise.

Returns:

np.ndarray: Normalised array.

save_fit(json_pth: Path) None

Saves the target stain metadata to a json file.

Args:

json_pth (Path): The path to save the json file to.

Returns:

None

File Reading and Writing

exception beast.file_readers.SlideReadException(message='Could not read slide.')

Bases: Exception

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception beast.file_readers.TileReadException(message='Could not read tile.')

Bases: Exception

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

beast.file_readers.read_tile(tile_pth: Path) ndarray

Read a tile image and return a numpy array.

Args:

tile_pth: Path to the tile image.

Returns:

Numpy array of the tile image.

beast.file_readers.read_wsi(slide_pth: Path) ndarray

Read a whole slide image and return a numpy array.

Args:

slide_pth: Path to the whole slide image.

Returns:

Numpy array of the whole slide image.

beast.file_writers.get_mpp(slide_pth)
beast.file_writers.write_ome_tiff(slide_arr: ndarray, mppx: float, mppy: float, output_path: Path, compression_arg: str = 'jpeg', levels: int = 8, level_zero_uncompressed=True) None

Write a whole slide image to a OME-TIFF file.

Args:

slide_arr <np.ndarray>: Numpy array of the whole slide image. mppx <float>: Microns per pixel in the x direction. mppy <float>: Microns per pixel in the y direction. compression_arg <str>: Compression to use for the OME-TIFF file. levels <int>: Number of levels to write to the OME-TIFF file. level_zero_uncompressed <bool>: Whether to write level zero uncompressed.

Returns:

None

Raises:

None

Notes:

beast.file_writers.write_tile(tile_arr: ndarray, output_path: Path) None

Write a tile to a file.

Args:

tile_arr <np.ndarray>: Numpy array of the tile. output_path <Path>: Path to write the tile to.

Tools and Utilities

class beast.tools.ParallelTileNormaliser(normalistion_class: ~beast.reinhard.ReinhardTileNormaliser | ~beast.macenko.MacenkoTileNormaliser | ~beast.vahadane.VahadaneTileNormaliser = <class 'beast.macenko.MacenkoTileNormaliser'>, discard_background: bool = False, background_threshold: float = 0.9, num_threads: int = 8, **kwargs)

Bases: object

Class to normalise a collection of tiles in parallel.

Args:

normalistion_class: The normalisation class to use. Must be one of ReinhardTileNormaliser, MacenkoTileNormaliser, VahadaneTileNormaliser num_threads (int): The number of threads to use for parallel processing. (Default: 8) **kwargs: The keyword arguments to pass to the normalisation class. See the documentation for the normalisation class for more information.

load_fit(json_path: Path) None

Loads the target stain metadata from a json file.

Args:

json_pth (Path): The path to load the json file from.

Returns:

dict: The target stain metadata.

normalise(targets: List[Path], output: List[Path] | Path) ndarray

Normalises a collection of tiles.

Args:

targets (List[Path]): The list of paths to the tiles to normalise. output (List[Path] | Path): The list of paths to save the normalised tiles to. If a single path to a directory is provided, the tiles will be saved in that directory.

class beast.tools.StainMetadataEstimator(normalistion_class: ~beast.reinhard.ReinhardTileNormaliser | ~beast.macenko.MacenkoTileNormaliser | ~beast.vahadane.VahadaneTileNormaliser | ~beast.reinhard.ReinhardWSINormaliser | ~beast.macenko.MacenkoWSINormaliser | ~beast.vahadane.VahadaneWSINormaliser = <class 'beast.macenko.MacenkoTileNormaliser'>, aggregation_method: ~beast.utils.AggregationMethod = AggregationMethod.MEDIAN, aggregation_percentile: float = 0.75, discard_background: bool = True, background_threshold: float = 0.9, **kwargs)

Bases: object

Class to estimate the stain metadata from a single tile or WSI or a list of them.

If a list of sources is provided, the stain matrix aggregation method can be set to one of “mean”, “median”, “max”, “min” or “percentile”.

Args:

normalistion_class: The normalisation class to use. Must be one of ReinhardTileNormaliser, MacenkoTileNormaliser, VahadaneTileNormaliser, ReinhardWSINormaliser, MacenkoWSINormaliser, VahadaneWSINormaliser aggregation_method (AggregationMethod): The method to use to aggregate the stain metadata from a list of sources. (Default: AggregationMethod.MEDIAN) percentile (float): The percentile to use when aggregating the stain metadata. Only used when aggregation_method=AggregationMethod.PERCENTILE **kwargs: Additional keyword arguments to pass to the normalisation class. See the documentation for the normalisation class for more details.

estimate(target: List[Path] | Path) dict

Estimates the stain metadata from a single tile or WSI or a list of them.

Args:

target (List[Path] | Path): The path to the tile or WSI or a list of them.

Returns:

dict: The estimated stain metadata.

save_fit(json_path: Path) None

Saves the target stain metadata to a json file.

Args:

json_path (Path): The path to save the json file to.

Returns:

None

class beast.tools.TesselatedWSINormaliser(normalistion_class: ~beast.reinhard.ReinhardTileNormaliser | ~beast.macenko.MacenkoTileNormaliser | ~beast.vahadane.VahadaneTileNormaliser = <class 'beast.macenko.MacenkoTileNormaliser'>, discard_background: str | None = None, background_threshold: float = 0.9, num_threads: int = 8, discard_non_conforming: bool = True, tile_ext='png', **kwargs)

Bases: object

Class to normalise a WSI through tesselation and normalisation of the individual tiles.

The tiles will then be written out to form a dataset of normalised tiles optionally the whole WSI can be reconstructed and returned.

Background tiles can be discarded by setting the discard_background to “threshold”.

The background_threshold parameter determines the percentage of background pixels present in the tile for the tile to be discarded.

Tiles will be written out in the format ystart_xstart_yend_xend.png

Args:

normalistion_class: The normalisation class to use. Must be one of ReinhardTileNormaliser, MacenkoTileNormaliser, VahadaneTileNormaliser discard_background: The method to use to discard background. Must be one of None, “threshold” background_threshold (float): The percentage of pixels in a tile that must be background for the tile to be discarded. Only used when discard_background=”otsu” discard_non_conforming (bool): Whether to discard tiles that do not conform to the target tile size. (Default: True) num_threads (int): The number of threads to use when tesselating and normalising the WSI. tile_ext (str): The extension to use for the tiles. (Default: “.png”) **kwargs: Additional keyword arguments to pass to the normalisation class. See the documentation for the normalisation class for more details.

load_fit(json_path: Path) None

Loads the target stain metadata from a json file.

Args:

json_pth (Path): The path to load the json file from.

Returns:

dict: The target stain metadata.

normalise(slide_path: Path, output_dir: Path, tile_size: tuple = (224, 224), return_slide: bool = False) None

Tesselates a WSI and normalises each tile.

Args:

slide_path (Path): The path to the WSI to normalise. output_dir (Path): The directory to write the normalised tiles to. tile_size (tuple): The size of the tiles to extract from the WSI. return_slide (bool): Whether to return the normalised slide. (Default: False)

class beast.utils.AggregationMethod(value)

Bases: Enum

Enum to define the method to use when aggregating the stain metadata from a list of sources.

MAX = 3
MEAN = 0
MEDIAN = 1
MIN = 2
PERCENTILE = 4
class beast.utils.IntensitySamplingMethod(value)

Bases: Enum

Enum to specify the method to use to sample the stain intensity.

MAX = 4
MEAN = 1
MEDIAN = 2
MIN = 3
PERCENTILE = 5
class beast.utils.TileCoordinate(xstart: int, ystart: int, xend: int, yend: int)

Bases: NamedTuple

NamedTuple for tile coordinates.

count(value, /)

Return number of occurrences of value.

index(value, start=0, stop=9223372036854775807, /)

Return first index of value.

Raises ValueError if the value is not present.

xend: int

Alias for field number 2

xstart: int

Alias for field number 0

yend: int

Alias for field number 3

ystart: int

Alias for field number 1

class beast.utils.TileDimensions(x: int, y: int)

Bases: NamedTuple

NamedTuple for tile dimensions.

count(value, /)

Return number of occurrences of value.

index(value, start=0, stop=9223372036854775807, /)

Return first index of value.

Raises ValueError if the value is not present.

x: int

Alias for field number 0

y: int

Alias for field number 1

beast.utils.generate_tile_coordinates(dimensions: tuple, tile_size: tuple = (5000, 5000), xstart: int = 0, ystart: int = 0) List[TileCoordinate]

Generate a list of tile coordinates for a given slide dimensions and patch size.

Args:

dimensions <Tuple>: Tuple of the slide dimensions (x,y). patch_size <Tuple>: Tuple of the tile size (x,y). xstart <Integer>: Starting x coordinate. ystart <Integer>: Starting y coordinate.

Returns:

List of tile coordinates <TileCoordinate>.

beast.utils.get_background_mask(tile_arr: ndarray, luminosity_threshold: float = 0.8, convert_to_lab=True) ndarray

Generate a background mask for a given tile.

Args:

tile_arr <np.ndarray>: Tile array. luminosity_threshold <Float>: Luminosity threshold.

Returns:

Tissue mask <np.ndarray>.

Notes:
  • Luminosity threshold is a value between 0 and 1.

  • Background mask is a binary mask with 0 for tissue and 1 for background.

beast.utils.get_otsu_tissue_mask(tile_arr: ndarray, convert_to_lab=True) ndarray

Generate a tissue mask for a given tile using Otsu’s method.

Args:

tile_arr <np.ndarray>: Tile array.

Returns:

Tissue mask <np.ndarray>.

Notes:
  • Tissue mask is a binary mask with 0 for tissue and 1 for background.

beast.utils.get_tissue_mask(tile_arr: ndarray, luminosity_threshold: float = 0.8, convert_to_lab=True) ndarray

Generate a tissue mask for a given tile.

Args:

tile_arr <np.ndarray>: Tile array. luminosity_threshold <Float>: Luminosity threshold.

Returns:

Tissue mask <np.ndarray>.

Notes:
  • Luminosity threshold is a value between 0 and 1.

  • Tissue mask is a binary mask with 0 for tissue and 1 for background.

beast.utils.lab_luminosity_standardiser(lab_arr: ndarray, percentile=98) ndarray

Standardise the luminosity of an LAB image.

Args:

lab_arr <np.ndarray>: LAB image.

Returns:

Standardised LAB image <np.ndarray>.

beast.utils.rgb_luminosity_standardiser(rgb: ndarray, percentile=98) ndarray

Standardise the luminosity of an RGB image.

Args:

rgb <np.ndarray>: RGB image.

Returns:

Standardised RGB image <np.ndarray>.