stainnormprogram 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. stainnormprogram/__about__.py +1 -0
  2. stainnormprogram/__init__.py +2 -0
  3. stainnormprogram/assessment/__init__.py +1 -0
  4. stainnormprogram/assessment/assessment.py +1186 -0
  5. stainnormprogram/assessment/background.py +211 -0
  6. stainnormprogram/assessment/color.py +770 -0
  7. stainnormprogram/assessment/contrast.py +252 -0
  8. stainnormprogram/assessment/gamut.py +407 -0
  9. stainnormprogram/assessment/palette.py +648 -0
  10. stainnormprogram/assessment/plot.py +759 -0
  11. stainnormprogram/assessment/structure.py +158 -0
  12. stainnormprogram/correction/__init__.py +1 -0
  13. stainnormprogram/correction/macenko.py +469 -0
  14. stainnormprogram/io/__init__.py +0 -0
  15. stainnormprogram/io/write_slide.py +119 -0
  16. stainnormprogram/library/TCGA-Manifest.txt +31 -0
  17. stainnormprogram/library/TCIA-Instructions.md +15 -0
  18. stainnormprogram/library/library.md +14 -0
  19. stainnormprogram/norm/__init__.py +1 -0
  20. stainnormprogram/norm/adjustments.py +88 -0
  21. stainnormprogram/norm/background.py +273 -0
  22. stainnormprogram/norm/normalization.py +126 -0
  23. stainnormprogram/norm/pipeline/__init__.py +0 -0
  24. stainnormprogram/norm/pipeline/macenko.py +302 -0
  25. stainnormprogram/norm/pipeline/pipeline.py +61 -0
  26. stainnormprogram/norm/style_estimation/__init__.py +0 -0
  27. stainnormprogram/norm/style_estimation/macenko.py +649 -0
  28. stainnormprogram/norm/subset.py +127 -0
  29. stainnormprogram/norm/translation/__init__.py +0 -0
  30. stainnormprogram/norm/translation/macenko.py +92 -0
  31. stainnormprogram/norm/utils.py +96 -0
  32. stainnormprogram/slide.py +1085 -0
  33. stainnormprogram-1.0.0.dist-info/METADATA +75 -0
  34. stainnormprogram-1.0.0.dist-info/RECORD +36 -0
  35. stainnormprogram-1.0.0.dist-info/WHEEL +4 -0
  36. stainnormprogram-1.0.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,119 @@
1
+ import os
2
+ from collections.abc import Callable
3
+ from typing import Any
4
+
5
+ import numpy as np
6
+ import tifffile
7
+ import zarr
8
+ import pyvips
9
+ import imagecodecs
10
+
11
+ SNP_DESCRIPTION = "Stain normalized using StainNormProgram."
12
+
13
+ class TiledWriter:
14
+
15
+ def __init__(self, output_filepath: str, shape: tuple[int], tile_size: int, mpp_x: float | None = None, mpp_y: float | None = None, maxworkers: int | None = None, compression: str | None = "zlib"):
16
+ """Write a pyramidal whole slide image using a tile generator.
17
+
18
+ Images outputted by this class can be opened using Aperio ImageScope or tifffile.
19
+ * Aperio ImageScope: https://www.leicabiosystems.com/us/digital-pathology/manage/aperio-imagescope/
20
+ * tifffile: https://github.com/cgohlke/tifffile
21
+
22
+ Args:
23
+ output_filepath: File path to save the output to.
24
+ shape: (H,W,3) or (H,W) pixel dimensions of the image.
25
+ tile_size: Pixel size of the tiles yielded by the generator.
26
+ mpp_x: Microns per pixel of the x-dimension.
27
+ mpp_y: Microns per pixel of the y-dimension.
28
+ maxworkers: Max number of workers to use. Automatically calculated if None.
29
+ compression: Compression to apply (None, "zlib", "jpeg").
30
+ """
31
+
32
+ if os.path.exists(output_filepath):
33
+ raise Exception(f"Output filepath {output_filepath} already exists.")
34
+
35
+ self.output_filepath = output_filepath
36
+ self.shape = shape
37
+ self.tile_size = tile_size
38
+ self.compression = compression
39
+ if mpp_x is not None and mpp_y is not None:
40
+ self.mpp_x = mpp_x
41
+ self.mpp_y = mpp_y
42
+ self.mpp_is_known = True
43
+ else:
44
+ self.mpp_x = None
45
+ self.mpp_y = None
46
+ self.mpp_is_known = False
47
+ self.maxworkers = maxworkers
48
+
49
+ if self.maxworkers is None:
50
+ self.maxworkers = max(1, (os.process_cpu_count() or 1) - 1)
51
+ print(f"Max workers for writing = {self.maxworkers}")
52
+
53
+ if len(self.shape) == 2:
54
+ self.shape = (self.shape[0], self.shape[1], 3)
55
+
56
+ def write(self, generator: Callable[[Any], np.ndarray]):
57
+ """Write the output image slide.
58
+
59
+ Args:
60
+ generator: A generator that yields tiles.
61
+ """
62
+
63
+ print("Writing file...")
64
+
65
+ if not self.mpp_is_known:
66
+ print("WARNING: Microns per pixel resolution is not known for this image.")
67
+
68
+ metadata = {
69
+ "PhysicalSizeX": self.mpp_x,
70
+ "PhysicalSizeXUnit": "um",
71
+ "PhysicalSizeY": self.mpp_y,
72
+ "PhysicalSizeYUnit": "um",
73
+ "Description": SNP_DESCRIPTION,
74
+ }
75
+
76
+ options = dict(
77
+ photometric="rgb",
78
+ resolutionunit="CENTIMETER" if self.mpp_is_known else None,
79
+ tile=(self.tile_size, self.tile_size),
80
+ compression=self.compression,
81
+ maxworkers=self.maxworkers,
82
+ dtype=np.uint8,
83
+ extratags=[
84
+ (34675, 7, None, imagecodecs.cms_profile('srgb'), True)
85
+ ]
86
+ )
87
+
88
+ # Highest resolution (base)
89
+ with tifffile.TiffWriter(self.output_filepath, bigtiff=True) as tif:
90
+ tif.write(
91
+ generator(),
92
+ shape=self.shape,
93
+ resolution=(1e4 / self.mpp_x, 1e4 / self.mpp_y) if self.mpp_is_known else None,
94
+ metadata=metadata,
95
+ **options,
96
+ )
97
+
98
+ # Pyramid resolutions
99
+ base = tifffile.imread(self.output_filepath, aszarr=True)
100
+ base_zarr = zarr.open(base, mode="r")
101
+
102
+ def pyramid_generator(zr, ds, ts):
103
+ for y in range(0, zr.shape[0], ts):
104
+ for x in range(0, zr.shape[1], ts):
105
+ yield zr[y:y+ts:ds, x:x+ts:ds, :]
106
+
107
+ with tifffile.TiffWriter(self.output_filepath, mode="r+") as tif:
108
+ for i in range(6):
109
+ ds_factor = 2 ** (i + 1)
110
+ tif.write(
111
+ pyramid_generator(base_zarr, ds_factor, self.tile_size * ds_factor),
112
+ shape=(self.shape[0] // ds_factor, self.shape[1] // ds_factor, 3),
113
+ resolution=(1e4 / self.mpp_x / ds_factor, 1e4 / self.mpp_y / ds_factor) if self.mpp_is_known else None,
114
+ **options,
115
+ )
116
+
117
+ base.close()
118
+
119
+ print(f"Finished writing file to {self.output_filepath}. Can be opened with Aperio ImageScope.")
@@ -0,0 +1,31 @@
1
+ id filename md5 size state
2
+ 93083f52-c5d6-4e38-bf34-1d9658d2a1eb TCGA-LL-A9Q3-01Z-00-DX1.94FA76F5-008A-401B-BFDC-817804BAE5F6.svs 2c23e8d0c4019edb8d5fcdce88a64670 1439635349 released
3
+ 411e68e5-a78e-486d-aba6-fdef038f9082 TCGA-LL-A442-01Z-00-DX1.9275EDBD-1C89-4AF3-B02B-19F613A4E083.svs a0413e5384a58716a1336739e70500b8 1483915041 released
4
+ 1db81db6-77eb-4aee-9e20-5d9cad3d4917 TCGA-LL-A740-01Z-00-DX1.757D94A5-EF0F-4A0E-99A9-8809B66438DA.svs 30a3478cbe551c75abb7f1d83e0a07d3 1266063965 released
5
+ 0b2e87e5-8168-4e31-ace7-ef06fb4a1e68 TCGA-LL-A5YP-01Z-00-DX1.ADA978DF-6625-4C4D-AE0C-F589B2BA4897.svs 96db1492383d3678aa1213e8301cff7b 1144621801 released
6
+ fd27d12b-3a78-4019-9587-991b672df809 TCGA-LL-A8F5-01Z-00-DX1.7579425E-1425-4160-A9DD-3D50F4C5428D.svs 181c61a6a0a8a216091936f5d4848b52 2364028443 released
7
+ ba28ec65-861d-4dc2-8ee2-8f5c38cb3804 TCGA-LL-A6FQ-01Z-00-DX1.D4FEEC16-FC67-4C4A-A4B1-F8BA34ECBCBD.svs 6284bafac29d50bbfaccce7ce7fd7192 1226267751 released
8
+ c6845ca3-df62-4186-8106-915cc22719f4 TCGA-LL-A50Y-01Z-00-DX1.7F08413F-2C59-4322-9296-84F8CD3DF619.svs 9c941a5f36c8ac465f20db4c2cf83bee 902187987 released
9
+ ab77596c-b37f-4ab2-9416-c5fbee2255b2 TCGA-LL-A73Z-01Z-00-DX1.C010142E-29C0-411D-9E0E-4B7D8A4C09BF.svs 096ea962fedfe53270b6ed78f104373a 468603959 released
10
+ 553c02d0-2c62-4513-bfc7-daef00be745e TCGA-LL-A7SZ-01Z-00-DX1.4DAF6421-6A1D-41C8-BFD6-859FE10CB8CC.svs 671dd903f9ae75fb60ea6e7aeb332a77 1709020943 released
11
+ 1e3d7e89-ee2c-46fd-8697-2e62886657fb TCGA-LL-A5YL-01Z-00-DX1.164C74AB-87D5-46CC-9D96-33FE1F88DC80.svs b0394b138fefd48d2a2f43b7900fa284 1281197011 released
12
+ 3f354f22-d0ef-43c4-880e-01e77c0bf4b8 TCGA-64-1677-01Z-00-DX1.7720D42B-1F57-4C23-9BC5-87C456E7737B.svs e0b68097e1edd8185bc8eed843cd9d28 690657835 released
13
+ 42a49b1b-70f8-4fb4-8bbe-e9c7afb7aa0e TCGA-64-1680-01Z-00-DX1.9CB14F20-E7B0-49A1-A327-404B3160FD65.svs 425a51f222c2a123ab20f10b856bc41d 470781403 released
14
+ 83f2728b-2ee0-4c90-857c-8567008bc6bc TCGA-64-5815-01Z-00-DX1.1E3600B5-7E83-47BE-AC70-E0C2D623740B.svs d31748045810a151c5d3a3c848e5c1c6 504937161 released
15
+ 15bcf2b1-bf72-4dae-8ea8-a9e992bf86dc TCGA-64-5775-01Z-00-DX1.9A338C1A-CDB6-41AF-B6D5-EDE608B5E3E1.svs 596beece8ca21018fde87182f45816c5 656496815 released
16
+ d80f62d3-7876-4684-87af-bfa9bc73dc29 TCGA-64-1678-01Z-00-DX1.92C851BD-37AC-4C4C-9920-DF394411CC2C.svs 64e451ec31bf92b1a440ccbe0cab1c10 287589441 released
17
+ 55684df0-a116-4adc-9296-403ca92aa44d TCGA-64-1676-01Z-00-DX1.3B8F1FAC-0FB2-45DE-AFA1-6ED451A4A61B.svs 56e09cd42f1410cbb424c933aaca194f 390849885 released
18
+ b802f195-c4c6-4fe4-9b1f-3c59027f4120 TCGA-64-5774-01Z-00-DX1.5E3B95EB-BF45-4687-BCF7-AA2A41AA806C.svs 84666aec6655c6554e126f451f4f0b90 340857143 released
19
+ 7c4036ba-3945-49de-b730-2f252a1d9808 TCGA-64-1681-01Z-00-DX1.fb0244f6-51a8-4da2-b45c-38d8e02edab7.svs 0450dd84c215a713a51b124bfba7097c 193683967 released
20
+ f0a493a6-0a97-4d2e-a02c-ae472f3f9ffc TCGA-64-5781-01Z-00-DX1.81474D4D-6B48-473F-BAA9-ABD75C9223C3.svs 9b6272612ba7d48ce8e870c55cfd0dc0 398720559 released
21
+ 69b5b476-9c48-46fa-ab6d-f9f6512a0ca6 TCGA-64-5779-01Z-00-DX1.B3268447-DCE0-4927-B5A9-EC4D61E9B17D.svs 68844021b711a415e1fa2f0217271072 1164566593 released
22
+ 60a64a3c-470c-4828-a12a-051c9b2589c2 TCGA-FP-8209-01Z-00-DX1.a5e13081-1631-44d4-8d6a-c229a22c2311.svs cf7a6f8f170a214244461ca4b3200adb 190800553 released
23
+ 195852bc-d771-462e-bdf7-93ff0b2da52d TCGA-FP-A4BF-01Z-00-DX1.D4E8128B-A783-45ED-BF0E-93650F9483EC.svs 1459089bc7975b54c1a3644859687568 477649386 released
24
+ ac099459-b3f4-42c8-9414-552d1939967f TCGA-FP-A4BE-01Z-00-DX1.813B0887-ED1F-48DD-A2E2-F14EB20D1F71.svs 97295bc9874cb459674b93fb2ed9747c 803784576 released
25
+ 23ca6340-3b44-4c1e-a7a5-ecf0f3d2dbc5 TCGA-FP-7735-01Z-00-DX1.97aac46a-898e-4c43-8c93-1496f40c43ed.svs 75112f76095d4658de0e1dc5aff31b21 120004149 released
26
+ c440f939-cda8-4c9d-9f9b-dd45daca0925 TCGA-FP-A9TM-01Z-00-DX1.1BD7C378-9FDD-46F0-B546-BB255079AFAA.svs a09a36a592867a59bb6ddbf8f94c94ca 47749264 released
27
+ 8d5a45a2-5bc1-4a92-9efc-c166dd076b37 TCGA-FP-A8CX-01Z-00-DX1.AD598CBF-2E0F-4285-A2BB-E9CE0EE1873B.svs 34eb1f628863f3b806588b571a70dd0e 31007036 released
28
+ 12bdfa01-6543-4eeb-a7bd-7c2b9d583950 TCGA-FP-8211-01Z-00-DX1.3906261e-914c-4191-802c-f27f64840211.svs 7dc8c553786458a3e37e519e6e2bd93b 177846579 released
29
+ 47764207-027a-4ef0-9219-737304efbef5 TCGA-FP-8631-01Z-00-DX1.8804336F-7DE6-4401-80B4-AEFA752C11B2.svs 515c45da43199d632825c1f49a3552e9 199411616 released
30
+ 3646d221-c089-4c55-bb06-ba2dd8fa6639 TCGA-FP-7916-01Z-00-DX1.6264d8c6-0ddb-4905-ad0c-146e380ddee1.svs e33e25786b22af3267fca0114a2f848b 133302121 released
31
+ 6c17329b-af08-47b2-930e-677f7f54a694 TCGA-FP-7998-01Z-00-DX1.9f24585a-d609-4094-8170-b0f483606a18.svs 8a5432d64f7ff6583fad4fd8b77871c7 94721205 released
@@ -0,0 +1,15 @@
1
+ # TCIA Instructions
2
+
3
+ To download images from TCIA, you will need the [IBM Aspera Client (or Connect)](https://www.ibm.com/products/aspera/downloads#Client-deployed+software).
4
+
5
+ ## HANCOCK Dataset
6
+
7
+ The HANCOCK dataset is at https://www.cancerimagingarchive.net/collection/hancock/. The Download button will take you to the IBM Aspera file browser where you can select the images to download.
8
+
9
+ Two immunohistochemistry (IHC) slides with diaminobenzidine (DAB) chromogen tissue microarrays (TMAs) can be downloaded at these paths.
10
+ * Images / TMA_TumorCenter / CD3 / TumorCenter_CD3_block1.svs
11
+ * Images / TMA_TumorCenter / CD3 / TumorCenter_CD163_block14.svs
12
+
13
+ Two H&E tissue microarrays (TMAs) can be downloaded at these paths.
14
+ * Images / TMA_TumorCenter / HE / TumorCenter_HE_block1.svs
15
+ * Images / TMA_TumorCenter / HE / TumorCenter_HE_block10.svs
@@ -0,0 +1,14 @@
1
+ # Library
2
+
3
+ ## Publicly available images
4
+
5
+ Below is a list of publicly available images that you can use to try out StainNormProgram.
6
+
7
+ | Image Set | About | Access |
8
+ | :--- | :--- | :--- |
9
+ | TCGA | 30 H&E Whole Slide Images (TCGA-LL = Candler Hospital - Breast, TCGA-64 = Fox Chase - Lung, TCGA-FP = International Genomics Consortium - Stomach) | Download using the [NIH GDC Data Transfer Tool](https://gdc.cancer.gov/access-data/gdc-data-transfer-tool). Use [this manifest](TCGA-Manifest.txt) to get the specific files. |
10
+ | HANCOCK | 2 IHC DAB and 2 H&E Tissue Microarrays | Download from [TCIA using IBM Aspera Client/Connect](https://www.cancerimagingarchive.net/collection/hancock/). See [this instructions file](TCIA-Instructions.md). |
11
+
12
+ ## Target images
13
+
14
+ For H&E, you can choose one institution above to act as the target institution. For IHC, I am still looking for another publicly available dataset with IHC images to serve as the target.
@@ -0,0 +1 @@
1
+ from .normalization import Normalization
@@ -0,0 +1,88 @@
1
+ import pyvips
2
+ import numpy as np
3
+
4
+ class Adjustment:
5
+
6
+ def __init__(self, shift: int | None = None, gamma: float | None = None):
7
+ """
8
+ ``Adjustment`` allows you to apply pre- and post-processing operations on images.
9
+ For example, changing the brightness of an image before stain normalization.
10
+
11
+ **Note:** Only one type of adjustment is allowed (e.g., do not specify both shift and gamma).
12
+
13
+ Args:
14
+ shift: Add/subtract a value from the RGB values (which results in brightening/darkening).
15
+ gamma: Perform a gamma adjustment.
16
+ """
17
+
18
+ self.shift = None
19
+ self.gamma = None
20
+
21
+ if shift is not None:
22
+ self.shift = shift
23
+ elif gamma is not None:
24
+ self.gamma = gamma
25
+
26
+ def apply_shift(self, image: pyvips.Image | np.ndarray) -> pyvips.Image | np.ndarray:
27
+ """Apply a brightness shift.
28
+
29
+ Args:
30
+ image: Image to perform the brightness shift on.
31
+
32
+ Returns:
33
+ The image (same type as the input) with a brightness shift applied.
34
+ """
35
+ output = None
36
+
37
+ if isinstance(image, pyvips.Image):
38
+ output = image.cast("float")
39
+ output = output + self.shift
40
+ output = output.clamp(min=0, max=255)
41
+ output = output.cast("uchar")
42
+ elif isinstance(image, np.ndarray):
43
+ output = image.astype(np.float32)
44
+ output = output + self.shift
45
+ output = np.clip(output, 0, 255)
46
+ output = output.astype(np.uint8)
47
+ else:
48
+ raise Exception("image was not a Pyvips image nor a NumPy array.")
49
+
50
+ return output
51
+
52
+ def apply_gamma(self, image: np.ndarray) -> np.ndarray:
53
+ """Apply a gamma correction.
54
+
55
+ Args:
56
+ image: Image to perform the gamma correction on.
57
+
58
+ Returns:
59
+ A np.ndarray of the gamma corrected image.
60
+ """
61
+ output = None
62
+
63
+ if isinstance(image, np.ndarray):
64
+ output = np.pow(image, self.gamma)
65
+ else:
66
+ raise Exception("image must be a np.ndarray.")
67
+
68
+ return output
69
+
70
+ def apply(self, image: Any) -> Any:
71
+ """Apply the adjustment to the image.
72
+
73
+ Args:
74
+ image: Image to perform the adjustment on.
75
+
76
+ Returns:
77
+ The adjusted image.
78
+ """
79
+
80
+ output = None
81
+
82
+ if self.shift is not None:
83
+ output = self.apply_shift(image)
84
+
85
+ elif self.gamma is not None:
86
+ output = self.apply_gamma(image)
87
+
88
+ return output
@@ -0,0 +1,273 @@
1
+ from stainnormprogram.slide import Tile, SlideImage
2
+
3
+ import pyvips
4
+ import numpy as np
5
+ import colour
6
+ from fastdigest import TDigest
7
+ from skimage.color import rgb2hsv
8
+ from skimage.filters import threshold_otsu
9
+
10
+ def otsu_threshold_foreground(tile: Tile, flatten: bool = False) -> np.ndarray:
11
+ """Compute a foreground tissue mask using Otsu's thresholding.
12
+
13
+ Args:
14
+ tile: Image tile.
15
+ flatten: Output a flattened version of the tile.
16
+
17
+ Returns:
18
+ A np.ndarray for the foreground mask (True = tissue).
19
+ """
20
+
21
+ gray_tile = tile.gray()
22
+ if flatten:
23
+ gray_tile = gray_tile.reshape(-1)
24
+ thresh = threshold_otsu(gray_tile)
25
+ fg_mask = gray_tile < thresh
26
+ return fg_mask
27
+
28
+ def hsv_threshold_foreground(tile: Tile, s_threshold: float = 0.05, v_threshold: float = 0.15, flatten: bool = False) -> np.ndarray:
29
+ """Compute the foreground tissue mask using HSV thresholds.
30
+
31
+ HSV pixels with saturation greater than s_threshold and value (brightness) greater than v_threshold are considered foreground.
32
+
33
+ Args:
34
+ tile: Image tile.
35
+ s_threshold: HSV saturation threshold [0., 1.] where 0. is no saturation.
36
+ v_threshold: HSV value threshold [0., 1.] where 0. is black.
37
+ flatten: Output a flattened version of the tile.
38
+
39
+ Returns:
40
+ A np.ndarray for the foreground mask (True = tissue).
41
+ """
42
+ hsv_tile = tile.hsv()
43
+ if flatten:
44
+ hsv_tile = hsv_tile.reshape(-1,3)
45
+ s = hsv_tile[...,1]
46
+ v = hsv_tile[...,2]
47
+ fg_mask = (s > s_threshold) & (v > v_threshold)
48
+ return fg_mask
49
+
50
+ class HSVBackgroundEstimation:
51
+
52
+ def __init__(self, slide: SlideImage, s_threshold: float = 0.05, v_threshold: float = 0.5):
53
+ """Estimate the background color using HSV thresholds.
54
+
55
+ HSV pixels with saturation less than s_threshold and value (brightness) greater than v_threshold are used in the background estimation.
56
+
57
+ Args:
58
+ slide: Image to estimate the background of.
59
+ s_threshold: HSV saturation threshold [0., 1.] where 0. is no saturation.
60
+ v_threshold: HSV value threshold [0., 1.] where 0. is black.
61
+ """
62
+
63
+ self.image = slide
64
+ self.s_threshold = s_threshold
65
+ self.v_threshold = v_threshold
66
+
67
+ def compute(self, method: str, options: dict[str, Any] = {}) -> dict[str, np.ndarray]:
68
+ """Perform the background color estimation.
69
+
70
+ Args:
71
+ method: "tiled" for estimating from tiles, "pyvips" for estimating from the entire image via pyvips, and "thumbnail" for estimating from a thumbnail.
72
+ options: Options for the specific compute method.
73
+
74
+ Returns:
75
+ A dictionary containing the requested computations.
76
+ """
77
+ print(f"Computing background estimation for {self.image.identifier}...")
78
+
79
+ if method == "tiled":
80
+ return self.tiled_compute(**options)
81
+ elif method == "pyvips":
82
+ return self.pyvips_compute(**options)
83
+ elif method == "thumbnail":
84
+ return self.thumbnail_compute(**options)
85
+ else:
86
+ raise Exception(f"{method} is not a valid method.")
87
+
88
+ def thumbnail_compute(self, height: int = 4096, smooth: bool = True, use_otsu: bool = False) -> dict[str, np.ndarray]:
89
+ """Compute the background using a thumbnail.
90
+
91
+ Args:
92
+ height: Max height of the thumbnail.
93
+ smooth: Allow for interpolation that performs pixel smoothing.
94
+ use_otsu: Use Otsu's thresholding to identify the background.
95
+
96
+ Returns:
97
+ A dictionary containing the median background color.
98
+ """
99
+ pixels = self.image.get_thumbnail(height=height, smooth=smooth) # (H,W,3) RGB uint8
100
+
101
+ if use_otsu:
102
+ otsu_mask = self.image.get_thumbnail_mask(otsu_threshold_foreground) # (H,W) True = foreground
103
+ candidate_bgd_pixels = pixels[~otsu_mask] # (N,3)
104
+ else:
105
+ candidate_bgd_pixels = pixels.reshape((-1,3))
106
+
107
+ hsv_pixels = rgb2hsv(candidate_bgd_pixels / 255.)
108
+ hsv_mask = (hsv_pixels[:,1] < self.s_threshold) & (hsv_pixels[:,2] > self.v_threshold) # (N,) True = background
109
+
110
+ bgd_pixels = candidate_bgd_pixels[hsv_mask]
111
+
112
+ I0 = np.median(bgd_pixels, axis=0)
113
+
114
+ return {"median": I0}
115
+
116
+ def tiled_compute(self, percentile: int = 50, max_pixels: int = 10_000_000, tile_size: int = 256, stability_check_interval: int = 10, stability_window: int = 3) -> dict[str, np.ndarray]:
117
+ """Compute the background using full resolution tiles.
118
+
119
+ Args:
120
+ percentile: Background percentile to compute (50 = median).
121
+ max_pixels: If the number of pixels used goes over max_pixels, stop the computation.
122
+ tile_size: Tile size to use.
123
+ stability_check_interval: Check for stability every ``stability_check_interval`` number of updates to the running background color.
124
+ stability_window: Number of stability checks that must pass before finishing the computation.
125
+
126
+ Returns:
127
+ A dictionary containing the requested background color.
128
+ """
129
+
130
+ # Tile size
131
+ self.image.set_tile_size(tile_size)
132
+
133
+ digests = [TDigest(), TDigest(), TDigest()]
134
+ self.image.set_mode("random")
135
+ n_pixels = 0
136
+ n_updates = 0
137
+ n_stable = 0
138
+
139
+ I0 = [None, None, None]
140
+
141
+ for i, (tile, _) in enumerate(self.image):
142
+
143
+ if i % 10 == 0:
144
+ print(f"Processed {i} tiles so far...")
145
+
146
+ tile_rgb = tile.rgb(as_uint8=True).reshape(-1,3) # (N,3)
147
+ tile_hsv = tile.hsv().reshape(-1,3)
148
+
149
+ tile_s = tile_hsv[:,1]
150
+ tile_v = tile_hsv[:,2]
151
+ mask = (tile_s < self.s_threshold) & (tile_v > self.v_threshold)
152
+
153
+ filtered = tile_rgb[mask] # (M,3)
154
+
155
+ if filtered.size == 0:
156
+ continue
157
+
158
+ n_pixels += filtered.shape[0]
159
+
160
+ for i in range(3):
161
+ digests[i].batch_update(filtered[:,i].tolist())
162
+ n_updates += 1
163
+
164
+ # Absolute stopping condition
165
+ if n_pixels > max_pixels:
166
+ break
167
+
168
+ # Check for convergence
169
+ if n_updates % stability_check_interval == 0:
170
+ same = True
171
+ for i in range(3):
172
+ same = same and (I0[i] == round(digests[i].percentile(percentile)))
173
+ I0[i] = round(digests[i].percentile(percentile))
174
+ if same:
175
+ n_stable += 1
176
+ else:
177
+ n_stable = 0
178
+ if n_stable >= stability_window:
179
+ break
180
+
181
+ for i in range(3):
182
+ I0[i] = round(digests[i].percentile(percentile))
183
+ I0 = np.array(I0).clip(0, 255).astype(np.uint8)
184
+
185
+ if percentile == 50:
186
+ return {"median": I0}
187
+ else:
188
+ return {str(percentile): I0}
189
+
190
+ def _compute_percentile(self, masked_rgb: pyvips.Image, percentile: int) -> np.ndarray:
191
+ """Compute the RGB value at a certain percentile for a pyvips image.
192
+
193
+ Args:
194
+ masked_rgb: Masked (non-background should be 0, background should be the original RGB value) pyvips image.
195
+ percentile: Percentile to compute (50 = median).
196
+
197
+ Returns:
198
+ A np.ndarray of the computed RGB pixel value.
199
+ """
200
+
201
+ percentile_rgb = []
202
+ for i in range(3):
203
+ channel_hist = masked_rgb[i].hist_find().numpy()
204
+ channel_hist = np.squeeze(channel_hist)
205
+ channel_hist[0] = 0
206
+ cdf = 100.0 * np.cumsum(channel_hist) / np.sum(channel_hist)
207
+ val = np.searchsorted(cdf, percentile)
208
+ percentile_rgb.append(val.item())
209
+ percentile_rgb = np.array(percentile_rgb)
210
+ return percentile_rgb
211
+
212
+ def pyvips_compute(self, measures: list[str | int] = ["median"], downsample_factor: float = 1.0, downsample_kernel: str = "nearest", **kwargs) -> dict[str, np.ndarray]:
213
+ """Compute the background using a pyvips image.
214
+
215
+ Args:
216
+ measures: Measures to compute ("median", "mean", "iqr", "std", or an int for percentile).
217
+ downsample_factor: Factor to downsample the image by. Must be in the interval (0.0, 1.0].
218
+ downsample_kernel: Kernel to use for downsampling ("nearest", "linear", "cubic", or any other pyvips kernel).
219
+
220
+ Returns:
221
+ A dictionary containing the requested computations.
222
+ """
223
+
224
+ image = self.image.get_pyvips()
225
+
226
+ if not isinstance(measures, list):
227
+ measures = [measures]
228
+
229
+ # Downsample
230
+ if downsample_factor <= 0.0 or downsample_factor > 1.0:
231
+ raise Exception("downsample_factor must be in the interval (0.0, 1.0]")
232
+ if downsample_factor < 1.0:
233
+ image = image.resize(downsample_factor, kernel=downsample_kernel)
234
+
235
+ # Convert to HSV
236
+ hsv_image = image.colourspace("hsv")
237
+
238
+ # Threshold
239
+ s_image = hsv_image[1]
240
+ v_image = hsv_image[2]
241
+
242
+ mask = (s_image < self.s_threshold * 255) & (v_image > self.v_threshold * 255)
243
+ masked_rgb = mask.ifthenelse(image, 0)
244
+ area = mask.height * mask.width
245
+ mask_sum = mask.avg() * area
246
+
247
+ results = {}
248
+ for measure in measures:
249
+ if measure == "mean":
250
+ mean_rgb = []
251
+ for i in range(3):
252
+ mean_val = masked_rgb[i].avg() * area / mask_sum * 255
253
+ mean_rgb.append(mean_val)
254
+ mean_rgb = np.array(mean_rgb)
255
+ results["mean"] = mean_rgb
256
+ elif measure == "std":
257
+ std_rgb = []
258
+ for i in range(3):
259
+ std_val = (masked_rgb[i].deviate() ** 2 * area / mask_sum) ** 0.5
260
+ std_rgb.append(std_val)
261
+ std_rgb = np.array(std_rgb)
262
+ results["std"] = std_rgb
263
+ elif measure == "median":
264
+ results["median"] = self._compute_percentile(masked_rgb, 50)
265
+ elif measure == "iqr":
266
+ results["iqr"] = self._compute_percentile(masked_rgb, 75) - self._compute_percentile(masked_rgb, 25)
267
+ elif isinstance(measure, int):
268
+ results[measure] = self._compute_percentile(masked_rgb, measure)
269
+ else:
270
+ raise Exception(f"{measure} is not a valid measure")
271
+
272
+ return results
273
+
@@ -0,0 +1,126 @@
1
+ from stainnormprogram.norm.pipeline.pipeline import Pipeline
2
+ from stainnormprogram.norm.pipeline.macenko import MacenkoPipeline
3
+ from stainnormprogram.norm.utils import add_images_to_dict, validate_json
4
+ from stainnormprogram.norm.subset import Subset
5
+
6
+ import os
7
+
8
+ class Normalization:
9
+
10
+ def __init__(self):
11
+ """Perform stain normalization.
12
+ """
13
+ self.target = {}
14
+ self.source = {}
15
+ self.target_json = None
16
+ self.pipeline = None
17
+
18
+ def __repr__(self):
19
+ return f"Normalization=(\n \
20
+ target={self.target}\n \
21
+ target_json={self.target_json}\n \
22
+ source={self.source}\n \
23
+ pipeline={self.pipeline}\n)"
24
+
25
+ def update_dict(self, items: list[str | Subset] | str | Subset, mydict: dict[str, SlideImage | Subset], allow_subsets: bool = True):
26
+ """Helper function for updating the self.target and self.source dictionaries.
27
+
28
+ Args:
29
+ items: Items (paths or Subsets) to add to the dictionary.
30
+ mydict: Dictionary to add items to.
31
+ allow_subsets: Allow Subsets to be added. Otherwise, only paths can be accepted.
32
+ """
33
+
34
+ if isinstance(items, (str, Subset)):
35
+ items = [items]
36
+
37
+ for item in items:
38
+ if isinstance(item, Subset):
39
+ if not allow_subsets:
40
+ raise Exception("Subsets are not accepted.")
41
+ subset_id = item.identifier
42
+ if subset_id not in mydict:
43
+ mydict[subset_id] = item
44
+
45
+ elif isinstance(item, str):
46
+ add_images_to_dict(item, mydict)
47
+
48
+ def set_target(self, target: str | list[str]):
49
+ """Add target images or a target style.
50
+
51
+ If list, the target style is averaged across all target images.
52
+
53
+ Args:
54
+ target: A path to an image or directory of images, or a list of paths/directories, or a string to a target style JSON.
55
+ """
56
+ if isinstance(target, str) and target.endswith(".json"):
57
+ validate_json(target)
58
+ self.target_json = target
59
+ else:
60
+ self.update_dict(target, self.target, allow_subsets=False)
61
+
62
+ def set_source(self, source: str | list[str, Subset] | Subset):
63
+ """Add source images to normalize.
64
+
65
+ If str or list, the source style is calculated from each image individually. If you want the source style to be computed across several images or from a separate reference, create a Subset. If you want to add pre- or post-adjustments, create a Subset. If you want to use a style JSON as the source style (e.g., you performed correction), create a Subset.
66
+
67
+ Args:
68
+ source: A path to an image or directory of images, or a Subset, or a list of paths/directories/Subsets.
69
+ """
70
+ self.update_dict(source, self.source)
71
+
72
+ def set_pipeline(self, pipeline: str | Pipeline):
73
+ """Set a normalization pipeline.
74
+
75
+ Available pipelines:
76
+ * MacenkoPipeline
77
+
78
+ Args:
79
+ pipeline: The name of a pipeline or a Pipeline object.
80
+ """
81
+ if isinstance(pipeline, str):
82
+ if pipeline == "MacenkoPipeline":
83
+ self.pipeline = MacenkoPipeline()
84
+ else:
85
+ raise Exception(f"{pipeline} is not a valid Pipeline.")
86
+ elif isinstance(pipeline, Pipeline):
87
+ self.pipeline = pipeline
88
+ else:
89
+ raise Exception("pipeline must be a str or Pipeline.")
90
+
91
+ def run_norm(self, output_dir: str):
92
+ """Run normalization.
93
+
94
+ The target style will output to output_dir as target.json. For each source image that a style is calculated on, a source style will output to [ID].json. For Subset references, the reference style will output to [Subset ID]_reference.json.
95
+
96
+ Args:
97
+ output_dir: Directory to output files to. Must not exist; will be created.
98
+ """
99
+
100
+ # Checks
101
+ if os.path.exists(output_dir):
102
+ raise Exception("output_dir should not exist. output_dir will be created by this function.")
103
+ if self.pipeline is None:
104
+ raise Exception("No pipeline was set. Use set_pipeline.")
105
+ if (len(self.target) == 0 and self.target_json is None):
106
+ raise Exception("No target was set. Use set_target.")
107
+ if (len(self.target) > 0 and self.target_json is not None):
108
+ raise Exception("You cannot have both target images and a target JSON.")
109
+ if len(self.source) == 0:
110
+ raise Exception("No source images were set. Use set_source.")
111
+
112
+ # Set output_dir
113
+ os.makedirs(output_dir, exist_ok=False)
114
+ self.pipeline.set_output_dir(output_dir)
115
+
116
+ # Set target
117
+ if self.target_json is None:
118
+ self.pipeline.set_target(self.target)
119
+ else:
120
+ self.pipeline.set_target_from_json(self.target_json)
121
+
122
+ # Set source
123
+ self.pipeline.set_source(self.source)
124
+
125
+ # Run pipeline
126
+ self.pipeline.run()
File without changes