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.
- stainnormprogram/__about__.py +1 -0
- stainnormprogram/__init__.py +2 -0
- stainnormprogram/assessment/__init__.py +1 -0
- stainnormprogram/assessment/assessment.py +1186 -0
- stainnormprogram/assessment/background.py +211 -0
- stainnormprogram/assessment/color.py +770 -0
- stainnormprogram/assessment/contrast.py +252 -0
- stainnormprogram/assessment/gamut.py +407 -0
- stainnormprogram/assessment/palette.py +648 -0
- stainnormprogram/assessment/plot.py +759 -0
- stainnormprogram/assessment/structure.py +158 -0
- stainnormprogram/correction/__init__.py +1 -0
- stainnormprogram/correction/macenko.py +469 -0
- stainnormprogram/io/__init__.py +0 -0
- stainnormprogram/io/write_slide.py +119 -0
- stainnormprogram/library/TCGA-Manifest.txt +31 -0
- stainnormprogram/library/TCIA-Instructions.md +15 -0
- stainnormprogram/library/library.md +14 -0
- stainnormprogram/norm/__init__.py +1 -0
- stainnormprogram/norm/adjustments.py +88 -0
- stainnormprogram/norm/background.py +273 -0
- stainnormprogram/norm/normalization.py +126 -0
- stainnormprogram/norm/pipeline/__init__.py +0 -0
- stainnormprogram/norm/pipeline/macenko.py +302 -0
- stainnormprogram/norm/pipeline/pipeline.py +61 -0
- stainnormprogram/norm/style_estimation/__init__.py +0 -0
- stainnormprogram/norm/style_estimation/macenko.py +649 -0
- stainnormprogram/norm/subset.py +127 -0
- stainnormprogram/norm/translation/__init__.py +0 -0
- stainnormprogram/norm/translation/macenko.py +92 -0
- stainnormprogram/norm/utils.py +96 -0
- stainnormprogram/slide.py +1085 -0
- stainnormprogram-1.0.0.dist-info/METADATA +75 -0
- stainnormprogram-1.0.0.dist-info/RECORD +36 -0
- stainnormprogram-1.0.0.dist-info/WHEEL +4 -0
- stainnormprogram-1.0.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
from stainnormprogram.norm.utils import add_images_to_dict
|
|
2
|
+
from stainnormprogram.slide import SlideImage, is_valid_extension
|
|
3
|
+
from stainnormprogram.norm.adjustments import Adjustment
|
|
4
|
+
|
|
5
|
+
class Subset:
|
|
6
|
+
|
|
7
|
+
def __init__(self, identifier: str):
|
|
8
|
+
"""Define a Subset of source images. Subsets enable greater control over the stain normalization process.
|
|
9
|
+
|
|
10
|
+
Args:
|
|
11
|
+
identifier: A unique name for this Subset.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
self.identifier = identifier
|
|
15
|
+
self.images = {}
|
|
16
|
+
self.reference = {}
|
|
17
|
+
self.reference_json = None
|
|
18
|
+
self.reference_pre_adjustments = {}
|
|
19
|
+
self.pre_adjustments = {}
|
|
20
|
+
self.post_adjustments = {}
|
|
21
|
+
self.global_pre_adjustment = None
|
|
22
|
+
self.global_post_adjustment = None
|
|
23
|
+
self.global_pre_adjustment_includes_reference = None
|
|
24
|
+
|
|
25
|
+
def __repr__(self):
|
|
26
|
+
return f"Subset=(\n \
|
|
27
|
+
identifier={self.identifier}\n \
|
|
28
|
+
images={self.images}\n \
|
|
29
|
+
reference={self.reference}\n \
|
|
30
|
+
reference_json={self.reference_json}\n)"
|
|
31
|
+
|
|
32
|
+
def add_images(self, images: str | list[str]):
|
|
33
|
+
"""Add images to the Subset.
|
|
34
|
+
|
|
35
|
+
You can call this function multiple times, which will accumulate images in the Subset.
|
|
36
|
+
|
|
37
|
+
Args:
|
|
38
|
+
images: a full path to an image or directory of images, or a list of paths/directories
|
|
39
|
+
"""
|
|
40
|
+
add_images_to_dict(images, self.images)
|
|
41
|
+
|
|
42
|
+
def set_global_pre_adjustment(self, adjustment: Adjustment | None, include_reference: bool = True):
|
|
43
|
+
"""Set a pre-adjustment for all images in this Subset.
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
adjustment: The Adjustment to apply to all images in this Subset.
|
|
47
|
+
include_reference: Apply the global pre-adjustment to the Subset's reference as well.
|
|
48
|
+
"""
|
|
49
|
+
if len(self.pre_adjustments) != 0:
|
|
50
|
+
raise Exception("You already have individual image pre-adjustments set. You cannot have a global pre-adjustment set at the same time.")
|
|
51
|
+
self.global_pre_adjustment = adjustment
|
|
52
|
+
self.global_pre_adjustment_includes_reference = include_reference
|
|
53
|
+
|
|
54
|
+
def set_global_post_adjustment(self, adjustment: Adjustment | None):
|
|
55
|
+
"""Set a post-adjustment for all images in this Subset.
|
|
56
|
+
|
|
57
|
+
Args:
|
|
58
|
+
adjustment: The Adjustment to apply to all images in this Subset.
|
|
59
|
+
"""
|
|
60
|
+
if len(self.post_adjustments) != 0:
|
|
61
|
+
raise Exception("You already have individual image post-adjustments set. You cannot have a global post-adjustment set at the same time.")
|
|
62
|
+
self.global_post_adjustment = adjustment
|
|
63
|
+
|
|
64
|
+
def add_pre_adjustments(self, adjustments: Adjustment | dict[str, Adjustment]):
|
|
65
|
+
"""Add individual image pre-adjustments to this Subset.
|
|
66
|
+
|
|
67
|
+
Args:
|
|
68
|
+
adjustments: If dict, key is the ID of the image (filename without extension) and value is Adjustment. If just Adjustment (not a dict), only one image can be in this Subset.
|
|
69
|
+
"""
|
|
70
|
+
if self.global_pre_adjustment is not None:
|
|
71
|
+
raise Exception("You already have a global pre-adjustment set. You cannot have individual image pre-adjustments set at the same time.")
|
|
72
|
+
self.add_adjustments_to_dict(adjustments, self.pre_adjustments, self.images)
|
|
73
|
+
|
|
74
|
+
def add_post_adjustments(self, adjustments: Adjustment | dict[str, Adjustment]):
|
|
75
|
+
"""Add individual image post-adjustments to this Subset.
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
adjustments: If dict, key is the ID of the image (filename without extension) and value is Adjustment. If just Adjustment (not a dict), only one image can be in this Subset.
|
|
79
|
+
"""
|
|
80
|
+
if self.global_post_adjustment is not None:
|
|
81
|
+
raise Exception("You already have a global post-adjustment set. You cannot have individual image post-adjustments set at the same time.")
|
|
82
|
+
self.add_adjustments_to_dict(adjustments, self.post_adjustments, self.images)
|
|
83
|
+
|
|
84
|
+
def add_adjustments_to_dict(self, adjustment: Adjustment | dict[str, Adjustment], mydict: dict[str, Adjustment], images_dict: dict[str, SlideImage]):
|
|
85
|
+
"""Helper function to add Adjustments to a dictionary.
|
|
86
|
+
|
|
87
|
+
Args:
|
|
88
|
+
adjustments: If dict, key is the ID of the image (filename without extension) and value is Adjustment. If just Adjustment (not a dict), only one image can be in this Subset.
|
|
89
|
+
mydict: Dictionary of Adjustments.
|
|
90
|
+
images_dict: Dictionary of SlideImages.
|
|
91
|
+
"""
|
|
92
|
+
if isinstance(adjustment, Adjustment):
|
|
93
|
+
if len(images_dict) > 1:
|
|
94
|
+
raise Exception("You have multiple images. Please provide adjustments as a dict with the key being the ID of the image (filename without extension) and value being the Adjustment.")
|
|
95
|
+
if len(images_dict) == 0:
|
|
96
|
+
raise Exception("Add images first before adding adjustments.")
|
|
97
|
+
adjustment = {images_dict.keys()[0]: adjustment}
|
|
98
|
+
|
|
99
|
+
mydict.update(adjustment)
|
|
100
|
+
|
|
101
|
+
def add_reference(self, reference: str | list[str], pre_adjustments: Adjustment | dict[str, Adjustment] | None = None):
|
|
102
|
+
"""Add reference image(s) for this source Subset. This is not the same as a target image.
|
|
103
|
+
|
|
104
|
+
When a reference is added, the source stain style for this Subset is estimated from the reference. The color transformation is then performed on the images added to the Subset.
|
|
105
|
+
This allows you to have fine-grained control over which images are used for style estimation and which images are color transformed.
|
|
106
|
+
|
|
107
|
+
The images added to the Subset can be the same as the images added as reference (i.e., when using multiple images to calculate an average source style).
|
|
108
|
+
|
|
109
|
+
Args:
|
|
110
|
+
reference: Path to an image or directory of images, or a list of paths/directories, or a JSON to a reference style.
|
|
111
|
+
pre_adjustments: If dict, key is the ID of the image (filename without extension) and value is Adjustment. If just Adjustment (not a dict), only one image can be the reference.
|
|
112
|
+
"""
|
|
113
|
+
if isinstance(reference, str) and reference.endswith(".json"):
|
|
114
|
+
if len(self.reference) != 0:
|
|
115
|
+
raise Exception("A reference was already set.")
|
|
116
|
+
self.reference_json = reference
|
|
117
|
+
return
|
|
118
|
+
|
|
119
|
+
if self.reference_json is not None:
|
|
120
|
+
raise Exception("A reference JSON was already set.")
|
|
121
|
+
|
|
122
|
+
add_images_to_dict(reference, self.reference)
|
|
123
|
+
|
|
124
|
+
if pre_adjustments is not None:
|
|
125
|
+
if self.global_pre_adjustment is not None and self.global_pre_adjustment_includes_reference:
|
|
126
|
+
raise Exception("A global pre-adjustment that includes the reference was already set. Set includes_reference=False in the set_global_pre_adjustment function to specify a different adjustment.")
|
|
127
|
+
self.add_adjustments_to_dict(pre_adjustments, self.reference_pre_adjustments, self.reference)
|
|
File without changes
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
from stainnormprogram.norm.utils import nnls
|
|
2
|
+
from stainnormprogram.norm.adjustments import Adjustment
|
|
3
|
+
|
|
4
|
+
from collections.abc import Iterator
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import math
|
|
8
|
+
import tifffile
|
|
9
|
+
|
|
10
|
+
class MacenkoTranslation:
|
|
11
|
+
|
|
12
|
+
def __init__(
|
|
13
|
+
self,
|
|
14
|
+
slide: SlideImage,
|
|
15
|
+
targetSM: np.ndarray,
|
|
16
|
+
targetMaxC: np.ndarray,
|
|
17
|
+
targetI0: np.ndarray,
|
|
18
|
+
sourceSM: np.ndarray,
|
|
19
|
+
sourceMaxC: np.ndarray,
|
|
20
|
+
sourceI0: np.ndarray,
|
|
21
|
+
pre_adjustment: Adjustment | None = None,
|
|
22
|
+
post_adjustment: Adjustment | None = None,
|
|
23
|
+
use_nnls: bool = True,
|
|
24
|
+
):
|
|
25
|
+
"""Perform a color transformation on an image using Macenko's method.
|
|
26
|
+
|
|
27
|
+
Args:
|
|
28
|
+
slide: SlideImage to perform the translation on.
|
|
29
|
+
targetSM: Target stain matrix.
|
|
30
|
+
targetMaxC: Target maxC (robust maximum concentrations).
|
|
31
|
+
targetI0: Target initial intensity (background color).
|
|
32
|
+
sourceSM: Source stain matrix.
|
|
33
|
+
sourceMaxC: Source maxC (robust maximum concentrations).
|
|
34
|
+
sourceI0: Source initial intensity (background color).
|
|
35
|
+
pre_adjustment: Adjustment to apply before color transformation.
|
|
36
|
+
post_adjustment: Adjustment to apply after color transformation.
|
|
37
|
+
use_nnls: Use non-negative least squares for concentration estimates.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
self.slide = slide
|
|
41
|
+
self.targetSM = targetSM
|
|
42
|
+
self.targetMaxC = targetMaxC
|
|
43
|
+
self.targetI0 = targetI0
|
|
44
|
+
self.sourceSM = sourceSM
|
|
45
|
+
self.sourceMaxC = sourceMaxC
|
|
46
|
+
self.sourceI0 = sourceI0
|
|
47
|
+
self.pre_adjustment = pre_adjustment
|
|
48
|
+
self.post_adjustment = post_adjustment
|
|
49
|
+
self.use_nnls = use_nnls
|
|
50
|
+
|
|
51
|
+
self.scaling_factor = np.divide(targetMaxC, sourceMaxC)[:, np.newaxis]
|
|
52
|
+
|
|
53
|
+
self.slide.set_mode("sequential")
|
|
54
|
+
self.slide.set_adjustment(self.pre_adjustment)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def translate(self, return_metadata: bool = False) -> Iterator[np.ndarray | tuple[np.ndarray, dict[str, Any]]]:
|
|
58
|
+
"""Generator to perform translation.
|
|
59
|
+
|
|
60
|
+
Some parts have been taken from https://github.com/slideflow/slideflow/blob/master/slideflow/norm/macenko.py.
|
|
61
|
+
|
|
62
|
+
Args:
|
|
63
|
+
return_metadata: Return metadata about the tile.
|
|
64
|
+
|
|
65
|
+
Yields:
|
|
66
|
+
A np.ndarray of the transformed image tile, along with a metadata dictionary if return_metadata is True.
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
for tile, metadata in self.slide:
|
|
70
|
+
|
|
71
|
+
tile_od = tile.od(self.sourceI0)
|
|
72
|
+
h, w, _ = tile_od.shape
|
|
73
|
+
|
|
74
|
+
tile_od = tile_od.reshape(-1,3).transpose() # (3,N)
|
|
75
|
+
|
|
76
|
+
if self.use_nnls:
|
|
77
|
+
C = nnls(self.sourceSM, tile_od)
|
|
78
|
+
else:
|
|
79
|
+
C = np.linalg.lstsq(self.sourceSM, tile_od, rcond=None)[0]
|
|
80
|
+
|
|
81
|
+
C2 = C * self.scaling_factor
|
|
82
|
+
|
|
83
|
+
Inorm = np.exp(-self.targetSM.dot(C2))
|
|
84
|
+
if self.post_adjustment is not None:
|
|
85
|
+
Inorm = self.post_adjustment.apply(Inorm)
|
|
86
|
+
Inorm = Inorm * self.targetI0[:, np.newaxis]
|
|
87
|
+
Inorm = np.clip(Inorm, 0, 255).astype(np.uint8)
|
|
88
|
+
Inorm = np.reshape(Inorm.transpose(), (h, w, 3))
|
|
89
|
+
|
|
90
|
+
if return_metadata:
|
|
91
|
+
yield Inorm, metadata
|
|
92
|
+
yield Inorm
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
from stainnormprogram.slide import SlideImage, is_valid_extension
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import os
|
|
5
|
+
|
|
6
|
+
def nnls(HE: np.ndarray, Y: np.ndarray) -> np.ndarray:
|
|
7
|
+
"""Modified form of Lawson and Hanson non-negative least squares.
|
|
8
|
+
|
|
9
|
+
Args:
|
|
10
|
+
HE: The stain matrix. HE should be a 3x2 matrix.
|
|
11
|
+
Y: The optical density (OD) values. Y should be a 3xN matrix.
|
|
12
|
+
|
|
13
|
+
Returns:
|
|
14
|
+
A np.ndarray for concentration estimates. It will be a 2xN matrix.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
C = np.linalg.lstsq(HE, Y, rcond=None)[0] # (2,N)
|
|
18
|
+
|
|
19
|
+
negIdx = np.where(np.any(C < 0, axis=0))[0]
|
|
20
|
+
|
|
21
|
+
Y_neg = Y[:, negIdx]
|
|
22
|
+
C_neg = C[:, negIdx]
|
|
23
|
+
|
|
24
|
+
if Y_neg.size == 0:
|
|
25
|
+
return C
|
|
26
|
+
|
|
27
|
+
H = HE[:,0:1]
|
|
28
|
+
E = HE[:,1:2]
|
|
29
|
+
|
|
30
|
+
Eidx = C_neg[0,:] < 0
|
|
31
|
+
Hidx = ~Eidx
|
|
32
|
+
|
|
33
|
+
YE = Y_neg[:,Eidx]
|
|
34
|
+
YH = Y_neg[:,Hidx]
|
|
35
|
+
|
|
36
|
+
negNNLS = np.zeros((2, Y_neg.shape[1]))
|
|
37
|
+
|
|
38
|
+
if YH.size != 0:
|
|
39
|
+
CYH = np.linalg.lstsq(H, YH, rcond=None)[0]
|
|
40
|
+
negNNLS[0,Hidx] = CYH
|
|
41
|
+
if YE.size != 0:
|
|
42
|
+
CYE = np.linalg.lstsq(E, YE, rcond=None)[0]
|
|
43
|
+
negNNLS[1,Eidx] = CYE
|
|
44
|
+
|
|
45
|
+
C[:,negIdx] = negNNLS
|
|
46
|
+
|
|
47
|
+
return C
|
|
48
|
+
|
|
49
|
+
def get_paths_in_folder(folder_path: str) -> list[str]:
|
|
50
|
+
"""Helper function for getting valid image paths in a folder.
|
|
51
|
+
|
|
52
|
+
Args:
|
|
53
|
+
folder_path: Folder path.
|
|
54
|
+
|
|
55
|
+
Returns:
|
|
56
|
+
A list of str paths for valid image paths in the folder.
|
|
57
|
+
"""
|
|
58
|
+
paths = []
|
|
59
|
+
for file in os.listdir(folder_path):
|
|
60
|
+
full_path = os.path.join(folder_path, file)
|
|
61
|
+
if os.path.isfile(full_path) and is_valid_extension(full_path):
|
|
62
|
+
paths.append(full_path)
|
|
63
|
+
return paths
|
|
64
|
+
|
|
65
|
+
def add_images_to_dict(images: str | list[str], mydict: dict[str, SlideImage]):
|
|
66
|
+
"""Helper function for adding images to a dictionary.
|
|
67
|
+
|
|
68
|
+
Args:
|
|
69
|
+
images: Images to add to the dictionary.
|
|
70
|
+
mydict: The dictionary to add images to.
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
if isinstance(images, str):
|
|
74
|
+
images = [images]
|
|
75
|
+
|
|
76
|
+
if isinstance(images, list):
|
|
77
|
+
for path in images:
|
|
78
|
+
if not isinstance(path, str) or (not os.path.isfile(path) and not os.path.isdir(path)):
|
|
79
|
+
raise Exception(f"{path} is not a valid image or directory path.")
|
|
80
|
+
elif os.path.isfile(path) and is_valid_extension(path):
|
|
81
|
+
image_id = is_valid_extension(path, split=True)[0]
|
|
82
|
+
mydict[image_id] = SlideImage(path, identifier=image_id)
|
|
83
|
+
elif os.path.isdir(path):
|
|
84
|
+
for p in get_paths_in_folder(path):
|
|
85
|
+
image_id = is_valid_extension(p, split=True)[0]
|
|
86
|
+
mydict[image_id] = SlideImage(p, identifier=image_id)
|
|
87
|
+
|
|
88
|
+
def validate_json(json_path: str):
|
|
89
|
+
"""Check that the JSON path exists. If it doesn't exist, an Exception is thrown. Otherwise, nothing happens.
|
|
90
|
+
|
|
91
|
+
Args:
|
|
92
|
+
json_path: JSON path to check.
|
|
93
|
+
"""
|
|
94
|
+
|
|
95
|
+
if not os.path.exists(json_path):
|
|
96
|
+
raise Exception(f"{json_path} does not exist.")
|