Skip to content

API reference

Augmentation

augmentation

__all__ module-attribute

__all__ = ['Transform', 'OneOf', 'Compose', 'RandomFlip', 'RandomRotation', 'ColorJitter', 'GaussianBlur', 'MedianBlur', 'MotionBlur', 'JPEGCompression', 'SaltAndPepper', 'GaussianNoise', 'StainNormalizationTransform']

Transform

Bases: ABC

Base class for image augmentations.

Every augmentation that inherits from this class should implement the apply method, which contains the actual image augmentation logic.

The augmentation is applied with probability prob. If the augmentation is not applied, the original image is returned.

Parameters:

Name Type Description Default
prob float, (default=0.5)

Probability of applying the augmentation. The value should be in the range [0.0, 1.0].

0.5
Source code in src/histokit/augmentation/base.py
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
class Transform(ABC):
    """
    Base class for image augmentations.

    Every augmentation that inherits from this class should implement
    the `apply` method, which contains the actual image augmentation logic.

    The augmentation is applied with probability `prob`. If the augmentation
    is not applied, the original image is returned.

    Parameters
    ----------
    prob : float, (default=0.5)
        Probability of applying the augmentation. The value should be in the
        range [0.0, 1.0].
    """
    def __init__(self, prob=0.5):
        """
        Initialize the augmentation.

        Parameters
        ----------
        prob : float, default=0.5
            Probability of applying the augmentation.
        """
        self.prob = prob

    def __call__(self, img: np.ndarray) -> np.ndarray:
        """
        Apply the augmentation to an image.

        The augmentation is applied only when a randomly generated value
        is lower than `prob`.

        Parameters
        ----------
        img : np.ndarray
            Input image represented as a NumPy array.

        Returns
        -------
        np.ndarray
            Augmented image, or the original image if the augmentation
            was not applied.
        """
        if random.random() < self.prob:
            return self.apply(img)
        return img

    @abstractmethod
    def apply(self, img: np.ndarray) -> np.ndarray:
        """
        Perform the augmentation.

        This abstract method must be implemented by all subclasses of
        `Transform`.

        Parameters
        ----------
        img : np.ndarray
            Input image represented as a NumPy array.

        Returns
        -------
        np.ndarray
            Augmented image.
        """
        pass

__init__

__init__(prob=0.5)

Initialize the augmentation.

Parameters:

Name Type Description Default
prob float

Probability of applying the augmentation.

0.5
Source code in src/histokit/augmentation/base.py
21
22
23
24
25
26
27
28
29
30
def __init__(self, prob=0.5):
    """
    Initialize the augmentation.

    Parameters
    ----------
    prob : float, default=0.5
        Probability of applying the augmentation.
    """
    self.prob = prob

__call__

__call__(img: ndarray) -> np.ndarray

Apply the augmentation to an image.

The augmentation is applied only when a randomly generated value is lower than prob.

Parameters:

Name Type Description Default
img ndarray

Input image represented as a NumPy array.

required

Returns:

Type Description
ndarray

Augmented image, or the original image if the augmentation was not applied.

Source code in src/histokit/augmentation/base.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def __call__(self, img: np.ndarray) -> np.ndarray:
    """
    Apply the augmentation to an image.

    The augmentation is applied only when a randomly generated value
    is lower than `prob`.

    Parameters
    ----------
    img : np.ndarray
        Input image represented as a NumPy array.

    Returns
    -------
    np.ndarray
        Augmented image, or the original image if the augmentation
        was not applied.
    """
    if random.random() < self.prob:
        return self.apply(img)
    return img

apply abstractmethod

apply(img: ndarray) -> np.ndarray

Perform the augmentation.

This abstract method must be implemented by all subclasses of Transform.

Parameters:

Name Type Description Default
img ndarray

Input image represented as a NumPy array.

required

Returns:

Type Description
ndarray

Augmented image.

Source code in src/histokit/augmentation/base.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
@abstractmethod
def apply(self, img: np.ndarray) -> np.ndarray:
    """
    Perform the augmentation.

    This abstract method must be implemented by all subclasses of
    `Transform`.

    Parameters
    ----------
    img : np.ndarray
        Input image represented as a NumPy array.

    Returns
    -------
    np.ndarray
        Augmented image.
    """
    pass

OneOf

Source code in src/histokit/augmentation/base.py
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
class OneOf:
    def __init__(self, transforms, prob=0.5):
        """
        Randomly select and apply one augmentation from a list.

        `OneOf` groups multiple transformations and applies at most one of them
        during a single call. The whole operation is executed with probability
        `prob`.

        Parameters
        ----------
        transforms : list
            List of augmentations to choose from. Each element should be callable,
            for example an instance of a class inheriting from `Transform`.
        prob : float, default=0.5
            Probability of applying one of the augmentations.
        """
        self.transforms = transforms
        self.prob = prob

    def __call__(self, img: np.ndarray) -> np.ndarray:
        """
        Apply one randomly selected augmentation to an image.

        If a randomly generated value is lower than `prob`, one augmentation
        is selected from `transforms` and applied to the image. Otherwise,
        the original image is returned unchanged.

        Parameters
        ----------
        img : np.ndarray
            Input image represented as a NumPy array.

        Returns
        -------
        np.ndarray
            Image after applying one randomly selected transformation, or the
            original image if no transformation was applied.
        """
        if random.random() < self.prob:
            transform = random.choice(self.transforms)
            return transform(img)

        return img

__init__

__init__(transforms, prob=0.5)

Randomly select and apply one augmentation from a list.

OneOf groups multiple transformations and applies at most one of them during a single call. The whole operation is executed with probability prob.

Parameters:

Name Type Description Default
transforms list

List of augmentations to choose from. Each element should be callable, for example an instance of a class inheriting from Transform.

required
prob float

Probability of applying one of the augmentations.

0.5
Source code in src/histokit/augmentation/base.py
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
def __init__(self, transforms, prob=0.5):
    """
    Randomly select and apply one augmentation from a list.

    `OneOf` groups multiple transformations and applies at most one of them
    during a single call. The whole operation is executed with probability
    `prob`.

    Parameters
    ----------
    transforms : list
        List of augmentations to choose from. Each element should be callable,
        for example an instance of a class inheriting from `Transform`.
    prob : float, default=0.5
        Probability of applying one of the augmentations.
    """
    self.transforms = transforms
    self.prob = prob

__call__

__call__(img: ndarray) -> np.ndarray

Apply one randomly selected augmentation to an image.

If a randomly generated value is lower than prob, one augmentation is selected from transforms and applied to the image. Otherwise, the original image is returned unchanged.

Parameters:

Name Type Description Default
img ndarray

Input image represented as a NumPy array.

required

Returns:

Type Description
ndarray

Image after applying one randomly selected transformation, or the original image if no transformation was applied.

Source code in src/histokit/augmentation/base.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
def __call__(self, img: np.ndarray) -> np.ndarray:
    """
    Apply one randomly selected augmentation to an image.

    If a randomly generated value is lower than `prob`, one augmentation
    is selected from `transforms` and applied to the image. Otherwise,
    the original image is returned unchanged.

    Parameters
    ----------
    img : np.ndarray
        Input image represented as a NumPy array.

    Returns
    -------
    np.ndarray
        Image after applying one randomly selected transformation, or the
        original image if no transformation was applied.
    """
    if random.random() < self.prob:
        transform = random.choice(self.transforms)
        return transform(img)

    return img

Compose

Combine multiple augmentations into a sequential pipeline.

Augmentations are applied one after another in the order in which they are provided in transforms. The output of one augmentation becomes the input of the next augmentation.

Parameters:

Name Type Description Default
transforms list

List of augmentations to apply sequentially. Each element should be callable and accept a NumPy array as input.

required
Source code in src/histokit/augmentation/base.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
class Compose:
    """
    Combine multiple augmentations into a sequential pipeline.

    Augmentations are applied one after another in the order in which they
    are provided in `transforms`. The output of one augmentation becomes
    the input of the next augmentation.

    Parameters
    ----------
    transforms : list
        List of augmentations to apply sequentially. Each element should be
        callable and accept a NumPy array as input.
    """
    def __init__(self, transforms):
        """
        Initialize the augmentation pipeline.

        Parameters
        ----------
        transforms : list
            List of augmentations to apply in sequence.
        """
        self.transforms = transforms

    def __call__(self, img: np.ndarray) -> np.ndarray:
        """
        Apply all augmentations sequentially to an image.

        Parameters
        ----------
        img : np.ndarray
            Input image represented as a NumPy array.

        Returns
        -------
        np.ndarray
            Image after applying all augmentations in sequence.
        """
        for transform in self.transforms:
            img = transform(img)

        return img

__init__

__init__(transforms)

Initialize the augmentation pipeline.

Parameters:

Name Type Description Default
transforms list

List of augmentations to apply in sequence.

required
Source code in src/histokit/augmentation/base.py
134
135
136
137
138
139
140
141
142
143
def __init__(self, transforms):
    """
    Initialize the augmentation pipeline.

    Parameters
    ----------
    transforms : list
        List of augmentations to apply in sequence.
    """
    self.transforms = transforms

__call__

__call__(img: ndarray) -> np.ndarray

Apply all augmentations sequentially to an image.

Parameters:

Name Type Description Default
img ndarray

Input image represented as a NumPy array.

required

Returns:

Type Description
ndarray

Image after applying all augmentations in sequence.

Source code in src/histokit/augmentation/base.py
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
def __call__(self, img: np.ndarray) -> np.ndarray:
    """
    Apply all augmentations sequentially to an image.

    Parameters
    ----------
    img : np.ndarray
        Input image represented as a NumPy array.

    Returns
    -------
    np.ndarray
        Image after applying all augmentations in sequence.
    """
    for transform in self.transforms:
        img = transform(img)

    return img

GaussianBlur

Bases: Transform

Apply Gaussian blur to an image.

The blur strength is controlled by the standard deviation sigma, which is randomly sampled from sigma_range each time the transform is applied. Size of the Gaussian kernel is automatically determined based on the sampled sigma. Uniform random sampling is used for the sigma value.

Parameters:

Name Type Description Default
sigma_range tuple of float

Range from which the Gaussian sigma value is sampled.

(0.3, 2.0)
prob float, (default: 1.0)

Probability of applying the augmentation.

1.0
Source code in src/histokit/augmentation/noise.py
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class GaussianBlur(Transform):
    """
    Apply Gaussian blur to an image.

    The blur strength is controlled by the standard deviation `sigma`,
    which is randomly sampled from `sigma_range` each time the transform
    is applied. Size of the Gaussian kernel is automatically determined 
    based on the sampled `sigma`. Uniform random sampling is used for the `sigma` value.

    Parameters
    ----------
    sigma_range : tuple of float, default: (0.3, 2.0)
        Range from which the Gaussian sigma value is sampled.
    prob : float, (default: 1.0)
        Probability of applying the augmentation.
    """
    def __init__(self, sigma_range=(0.3, 2.0), prob=1.0):
        """
        Initialize the Gaussian blur augmentation.

        Parameters
        ----------
        sigma_range : tuple of float, default: (0.3, 2.0)
            Minimum and maximum sigma values used for Gaussian blur.
        prob : float, (default: 1.0)
            Probability of applying the augmentation.
        """
        super().__init__(prob)
        self.sigma_range = sigma_range

    def apply(self, img: np.ndarray) -> np.ndarray:
        """
        Apply Gaussian blur to the input image.

        Parameters
        ----------
        img : np.ndarray
            Input image represented as a NumPy array.

        Returns
        -------
        np.ndarray
            Blurred image.
        """
        sigma = random.uniform(*self.sigma_range)
        return cv2.GaussianBlur(img, (0, 0), sigma)

__init__

__init__(sigma_range=(0.3, 2.0), prob=1.0)

Initialize the Gaussian blur augmentation.

Parameters:

Name Type Description Default
sigma_range tuple of float

Minimum and maximum sigma values used for Gaussian blur.

(0.3, 2.0)
prob float, (default: 1.0)

Probability of applying the augmentation.

1.0
Source code in src/histokit/augmentation/noise.py
22
23
24
25
26
27
28
29
30
31
32
33
34
def __init__(self, sigma_range=(0.3, 2.0), prob=1.0):
    """
    Initialize the Gaussian blur augmentation.

    Parameters
    ----------
    sigma_range : tuple of float, default: (0.3, 2.0)
        Minimum and maximum sigma values used for Gaussian blur.
    prob : float, (default: 1.0)
        Probability of applying the augmentation.
    """
    super().__init__(prob)
    self.sigma_range = sigma_range

apply

apply(img: ndarray) -> np.ndarray

Apply Gaussian blur to the input image.

Parameters:

Name Type Description Default
img ndarray

Input image represented as a NumPy array.

required

Returns:

Type Description
ndarray

Blurred image.

Source code in src/histokit/augmentation/noise.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def apply(self, img: np.ndarray) -> np.ndarray:
    """
    Apply Gaussian blur to the input image.

    Parameters
    ----------
    img : np.ndarray
        Input image represented as a NumPy array.

    Returns
    -------
    np.ndarray
        Blurred image.
    """
    sigma = random.uniform(*self.sigma_range)
    return cv2.GaussianBlur(img, (0, 0), sigma)

MedianBlur

Bases: Transform

Apply median blur to an image.

The kernel size is randomly sampled from size_range. If the sampled size is even, it is increased by one (OpenCV median blur requires an odd kernel size). Uniform random sampling is used for the kernel size.

Parameters:

Name Type Description Default
size_range tuple of int

Range from which the median blur kernel size is sampled.

(3, 7)
prob float, (default: 1.0)

Probability of applying the transformation.

1.0
Source code in src/histokit/augmentation/noise.py
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
class MedianBlur(Transform):
    """
    Apply median blur to an image.

    The kernel size is randomly sampled from `size_range`. If the sampled
    size is even, it is increased by one (OpenCV median blur requires
    an odd kernel size). Uniform random sampling is used for the kernel size.

    Parameters
    ----------
    size_range : tuple of int, default: (3, 7)
        Range from which the median blur kernel size is sampled.
    prob : float, (default: 1.0)
        Probability of applying the transformation.
    """
    def __init__(self, size_range=(3, 7), prob=1.0):
        """
        Initialize the median blur transform.

        Parameters
        ----------
        size_range : tuple of int, default: (3, 7)
            Minimum and maximum kernel size values.
        prob : float, (default: 1.0)
            Probability of applying the transform.
        """
        super().__init__(prob)
        self.size_range = size_range

    def apply(self, img: np.ndarray) -> np.ndarray:
        """
        Apply median blur to the input image.

        Parameters
        ----------
        img : np.ndarray
            Input image represented as a NumPy array.

        Returns
        -------
        np.ndarray
            Image after applying median blur.
        """
        size = random.randint(*self.size_range)

        if size % 2 == 0:
            size += 1

        return cv2.medianBlur(img, size)

__init__

__init__(size_range=(3, 7), prob=1.0)

Initialize the median blur transform.

Parameters:

Name Type Description Default
size_range tuple of int

Minimum and maximum kernel size values.

(3, 7)
prob float, (default: 1.0)

Probability of applying the transform.

1.0
Source code in src/histokit/augmentation/noise.py
69
70
71
72
73
74
75
76
77
78
79
80
81
def __init__(self, size_range=(3, 7), prob=1.0):
    """
    Initialize the median blur transform.

    Parameters
    ----------
    size_range : tuple of int, default: (3, 7)
        Minimum and maximum kernel size values.
    prob : float, (default: 1.0)
        Probability of applying the transform.
    """
    super().__init__(prob)
    self.size_range = size_range

apply

apply(img: ndarray) -> np.ndarray

Apply median blur to the input image.

Parameters:

Name Type Description Default
img ndarray

Input image represented as a NumPy array.

required

Returns:

Type Description
ndarray

Image after applying median blur.

Source code in src/histokit/augmentation/noise.py
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
def apply(self, img: np.ndarray) -> np.ndarray:
    """
    Apply median blur to the input image.

    Parameters
    ----------
    img : np.ndarray
        Input image represented as a NumPy array.

    Returns
    -------
    np.ndarray
        Image after applying median blur.
    """
    size = random.randint(*self.size_range)

    if size % 2 == 0:
        size += 1

    return cv2.medianBlur(img, size)

MotionBlur

Bases: Transform

Apply motion blur to an image.

A linear blur kernel is created with a randomly sampled degree and then rotated by a randomly sampled angle. The resulting kernel is applied to the image using 2D convolution. Uniform random sampling is used for both the degree and angle of the motion blur.

Parameters:

Name Type Description Default
degree_range tuple of int

Range from which the motion blur kernel size is sampled. Higher values produce stronger blur.

(5, 15)
angle_range tuple of float

Range of rotation angles in degrees used for the motion blur direction.

(0, 360)
prob float

Probability of applying the transformation.

1.0
Source code in src/histokit/augmentation/noise.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
class MotionBlur(Transform):
    """
    Apply motion blur to an image.

    A linear blur kernel is created with a randomly sampled degree and then
    rotated by a randomly sampled angle. The resulting kernel is applied to
    the image using 2D convolution. Uniform random sampling is used for both 
    the degree and angle of the motion blur.

    Parameters
    ----------
    degree_range : tuple of int, default: (5, 15)
        Range from which the motion blur kernel size is sampled.
        Higher values produce stronger blur.
    angle_range : tuple of float, default: (0, 360)
        Range of rotation angles in degrees used for the motion blur direction.
    prob : float, default: 1.0
        Probability of applying the transformation.
    """
    def __init__(
        self,
        degree_range=(5, 15),
        angle_range=(0, 360),
        prob=1.0):

        super().__init__(prob)
        self.degree_range = degree_range
        self.angle_range = angle_range

    def apply(self, img: np.ndarray) -> np.ndarray:
        """
        Apply motion blur to the input image.

        Parameters
        ----------
        degree_range : tuple of int, optional
            Minimum and maximum motion blur kernel sizes.
        angle_range : tuple of float, optional
            Minimum and maximum motion blur angles in degrees.
        prob : float, optional
            Probability of applying the transform.
        """
        degree = random.randint(*self.degree_range)
        angle = random.uniform(*self.angle_range)

        kernel = np.zeros((degree, degree), dtype=np.float32)
        kernel[(degree - 1) // 2, :] = 1.0
        kernel /= degree

        M = cv2.getRotationMatrix2D(
            (degree / 2 - 0.5, degree / 2 - 0.5),
            angle,
            1.0,
        )

        kernel = cv2.warpAffine(
            kernel,
            M,
            (degree, degree),
        )

        return cv2.filter2D(img, -1, kernel)

apply

apply(img: ndarray) -> np.ndarray

Apply motion blur to the input image.

Parameters:

Name Type Description Default
degree_range tuple of int

Minimum and maximum motion blur kernel sizes.

required
angle_range tuple of float

Minimum and maximum motion blur angles in degrees.

required
prob float

Probability of applying the transform.

required
Source code in src/histokit/augmentation/noise.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
def apply(self, img: np.ndarray) -> np.ndarray:
    """
    Apply motion blur to the input image.

    Parameters
    ----------
    degree_range : tuple of int, optional
        Minimum and maximum motion blur kernel sizes.
    angle_range : tuple of float, optional
        Minimum and maximum motion blur angles in degrees.
    prob : float, optional
        Probability of applying the transform.
    """
    degree = random.randint(*self.degree_range)
    angle = random.uniform(*self.angle_range)

    kernel = np.zeros((degree, degree), dtype=np.float32)
    kernel[(degree - 1) // 2, :] = 1.0
    kernel /= degree

    M = cv2.getRotationMatrix2D(
        (degree / 2 - 0.5, degree / 2 - 0.5),
        angle,
        1.0,
    )

    kernel = cv2.warpAffine(
        kernel,
        M,
        (degree, degree),
    )

    return cv2.filter2D(img, -1, kernel)

JPEGCompression

Bases: Transform

Perform JPEG compression.

The image is compressed to JPEG format using a randomly sampled quality value The Lower quality values produce stronger compression artifacts.

Parameters:

Name Type Description Default
quality_range tuple of int

Range from which the JPEG quality value is sampled. Values should usually be between 0 and 100.

(10, 50)
prob float

Probability of applying the transformation.

1.0
Source code in src/histokit/augmentation/noise.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
class JPEGCompression(Transform):
    """
    Perform JPEG compression.

    The image is compressed to JPEG format using a randomly sampled quality value
    The Lower quality values produce stronger
    compression artifacts.

    Parameters
    ----------
    quality_range : tuple of int, default: (10, 50)
        Range from which the JPEG quality value is sampled.
        Values should usually be between 0 and 100.
    prob : float, default: 1.0
        Probability of applying the transformation.
    """
    def __init__(
        self,
        quality_range=(10, 50),
        prob=1.0,
    ):
        super().__init__(prob)
        self.quality_range = quality_range

    def apply(self, img: np.ndarray) -> np.ndarray:
        """
        Apply JPEG compression to the input image.

        Parameters
        ----------
        quality_range : tuple of int, default: (10, 50)
            Range from which the JPEG quality value is sampled.
        prob : float, default: 1.0
            Probability of applying the transform.
        """
        quality = random.randint(*self.quality_range)

        success, encoded = cv2.imencode(
            ".jpg",
            cv2.cvtColor(img, cv2.COLOR_RGB2BGR),
            [cv2.IMWRITE_JPEG_QUALITY, quality],
        )

        if not success:
            return img

        decoded = cv2.imdecode(
            encoded,
            cv2.IMREAD_COLOR,
        )

        return cv2.cvtColor(
            decoded,
            cv2.COLOR_BGR2RGB,
        )

apply

apply(img: ndarray) -> np.ndarray

Apply JPEG compression to the input image.

Parameters:

Name Type Description Default
quality_range tuple of int

Range from which the JPEG quality value is sampled.

(10, 50)
prob float

Probability of applying the transform.

1.0
Source code in src/histokit/augmentation/noise.py
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
def apply(self, img: np.ndarray) -> np.ndarray:
    """
    Apply JPEG compression to the input image.

    Parameters
    ----------
    quality_range : tuple of int, default: (10, 50)
        Range from which the JPEG quality value is sampled.
    prob : float, default: 1.0
        Probability of applying the transform.
    """
    quality = random.randint(*self.quality_range)

    success, encoded = cv2.imencode(
        ".jpg",
        cv2.cvtColor(img, cv2.COLOR_RGB2BGR),
        [cv2.IMWRITE_JPEG_QUALITY, quality],
    )

    if not success:
        return img

    decoded = cv2.imdecode(
        encoded,
        cv2.IMREAD_COLOR,
    )

    return cv2.cvtColor(
        decoded,
        cv2.COLOR_BGR2RGB,
    )

SaltAndPepper

Bases: Transform

Randomly add salt-and-pepper noise to an image.

This transform randomly replaces a fraction of image pixels with either white values, called salt, or black values, called pepper.

Parameters:

Name Type Description Default
amount_range tuple[float, float]

Range used to sample the fraction of pixels affected by noise. The sampled value is multiplied by the image area H * W to compute the number of noisy pixels.

(0.01, 0.05)
prob float

Probability of applying the transform.

1.0
Notes

The input image is expected to have pixel values in [0, 255]. The returned image has the same shape and dtype as the input image.

Source code in src/histokit/augmentation/noise.py
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
class SaltAndPepper(Transform):
    """Randomly add salt-and-pepper noise to an image.

    This transform randomly replaces a fraction of image pixels with either
    white values, called salt, or black values, called pepper.

    Parameters
    ----------
    amount_range : tuple[float, float], default=(0.01, 0.05)
        Range used to sample the fraction of pixels affected by noise.
        The sampled value is multiplied by the image area ``H * W`` to compute
        the number of noisy pixels.
    prob : float, default=1.0
        Probability of applying the transform.

    Notes
    -----
    The input image is expected to have pixel values in ``[0, 255]``.
    The returned image has the same shape and dtype as the input image.
    """
    def __init__(self, amount_range=(0.01, 0.05), prob=1.0):
        super().__init__(prob)
        self.amount_range = amount_range

    def apply(self, img: np.ndarray) -> np.ndarray:
        """Apply salt-and-pepper noise to an image.

        Parameters
        ----------
        img : np.ndarray
            Input image with shape ``(H, W)`` or ``(H, W, C)``.

        Returns
        -------
        np.ndarray
            Image with randomly selected pixels replaced by 0 or 255. The shape
            and dtype are the same as in ``img``.
        """
        arr = img.copy()
        amount = random.uniform(*self.amount_range)

        h, w = arr.shape[:2]
        num_pixels = int(amount * h * w)

        num_salt = num_pixels // 2
        num_pepper = num_pixels - num_salt

        ys = np.random.randint(0, h, num_salt)
        xs = np.random.randint(0, w, num_salt)
        arr[ys, xs] = 255

        ys = np.random.randint(0, h, num_pepper)
        xs = np.random.randint(0, w, num_pepper)
        arr[ys, xs] = 0

        return arr

apply

apply(img: ndarray) -> np.ndarray

Apply salt-and-pepper noise to an image.

Parameters:

Name Type Description Default
img ndarray

Input image with shape (H, W) or (H, W, C).

required

Returns:

Type Description
ndarray

Image with randomly selected pixels replaced by 0 or 255. The shape and dtype are the same as in img.

Source code in src/histokit/augmentation/noise.py
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
def apply(self, img: np.ndarray) -> np.ndarray:
    """Apply salt-and-pepper noise to an image.

    Parameters
    ----------
    img : np.ndarray
        Input image with shape ``(H, W)`` or ``(H, W, C)``.

    Returns
    -------
    np.ndarray
        Image with randomly selected pixels replaced by 0 or 255. The shape
        and dtype are the same as in ``img``.
    """
    arr = img.copy()
    amount = random.uniform(*self.amount_range)

    h, w = arr.shape[:2]
    num_pixels = int(amount * h * w)

    num_salt = num_pixels // 2
    num_pepper = num_pixels - num_salt

    ys = np.random.randint(0, h, num_salt)
    xs = np.random.randint(0, w, num_salt)
    arr[ys, xs] = 255

    ys = np.random.randint(0, h, num_pepper)
    xs = np.random.randint(0, w, num_pepper)
    arr[ys, xs] = 0

    return arr

GaussianNoise

Bases: Transform

Add random Gaussian noise to an image.

This transform samples a Gaussian noise distribution with random mean and standard deviation, adds the noise to the input image, and clips the result to the valid image intensity range [0, 255].

Parameters:

Name Type Description Default
mean_range tuple[float, float]

Range used to sample the Gaussian noise mean. The value is sampled as random.uniform(*mean_range).

(0.0, 6.0)
std_range tuple[float, float]

Range used to sample the Gaussian noise standard deviation. The value is sampled as random.uniform(*std_range).

(10.0, 30.0)
prob float

Probability of applying the transform.

1.0
Notes

The input image is expected to have pixel values in [0, 255]. The returned image has dtype np.uint8.

Source code in src/histokit/augmentation/noise.py
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
class GaussianNoise(Transform):
    """Add random Gaussian noise to an image.

    This transform samples a Gaussian noise distribution with random mean and
    standard deviation, adds the noise to the input image, and clips the result
    to the valid image intensity range ``[0, 255]``.

    Parameters
    ----------
    mean_range : tuple[float, float], default=(0.0, 6.0)
        Range used to sample the Gaussian noise mean. The value is sampled as
        ``random.uniform(*mean_range)``.
    std_range : tuple[float, float], default=(10.0, 30.0)
        Range used to sample the Gaussian noise standard deviation. The value is
        sampled as ``random.uniform(*std_range)``.
    prob : float, default=1.0
        Probability of applying the transform.

    Notes
    -----
    The input image is expected to have pixel values in ``[0, 255]``.
    The returned image has dtype ``np.uint8``.
    """
    def __init__(self, mean_range=(0.0, 6.0), std_range=(10.0, 30.0), prob=1.0):
        super().__init__(prob)
        self.mean_range = mean_range
        self.std_range = std_range

    def apply(self, img: np.ndarray) -> np.ndarray:
        """Apply Gaussian noise to an image.

        Parameters
        ----------
        img : np.ndarray
            Input image with shape ``(H, W)`` or ``(H, W, C)`` and pixel values
            in ``[0, 255]``.

        Returns
        -------
        np.ndarray
            Image with added Gaussian noise. The output has the same shape as
            ``img`` and dtype ``np.uint8``.
        """
        mean = random.uniform(*self.mean_range)
        std = random.uniform(*self.std_range)

        arr = img.astype(np.float32)
        noise = np.random.normal(mean, std, arr.shape)

        arr = arr + noise
        arr = np.clip(arr, 0, 255).astype(np.uint8)

        return arr

apply

apply(img: ndarray) -> np.ndarray

Apply Gaussian noise to an image.

Parameters:

Name Type Description Default
img ndarray

Input image with shape (H, W) or (H, W, C) and pixel values in [0, 255].

required

Returns:

Type Description
ndarray

Image with added Gaussian noise. The output has the same shape as img and dtype np.uint8.

Source code in src/histokit/augmentation/noise.py
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
def apply(self, img: np.ndarray) -> np.ndarray:
    """Apply Gaussian noise to an image.

    Parameters
    ----------
    img : np.ndarray
        Input image with shape ``(H, W)`` or ``(H, W, C)`` and pixel values
        in ``[0, 255]``.

    Returns
    -------
    np.ndarray
        Image with added Gaussian noise. The output has the same shape as
        ``img`` and dtype ``np.uint8``.
    """
    mean = random.uniform(*self.mean_range)
    std = random.uniform(*self.std_range)

    arr = img.astype(np.float32)
    noise = np.random.normal(mean, std, arr.shape)

    arr = arr + noise
    arr = np.clip(arr, 0, 255).astype(np.uint8)

    return arr

ColorJitter

Bases: Transform

Randomly adjust brightness, contrast, saturation, and hue.

This transform applies simple color augmentations to an RGB image. Brightness and contrast are adjusted directly in RGB space, while saturation and hue are adjusted in HSV color space.

Parameters:

Name Type Description Default
brightness_range tuple[float, float]

Range used to sample the brightness factor. The final factor is computed as 1.0 + random.uniform(*brightness_range).

(0, 0.3)
contrast_range tuple[float, float]

Range used to sample the contrast factor. The final factor is computed as 1.0 + random.uniform(*contrast_range).

(0, 0.3)
saturation_range tuple[float, float]

Range used to sample the saturation factor. The final factor is computed as 1.0 + random.uniform(*saturation_range).

(0, 0.3)
hue_range tuple[float, float]

Range used to sample the hue shift. Values are interpreted as fractions of OpenCV's hue range, where hue values are in [0, 179].

(0, 0.1)
prob float

Probability of applying the transform.

1.0
Notes

The input image is expected to be an RGB image with pixel values in [0, 255]. The returned image has dtype np.uint8.

Source code in src/histokit/augmentation/color.py
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
class ColorJitter(Transform):
    """Randomly adjust brightness, contrast, saturation, and hue.

    This transform applies simple color augmentations to an RGB image. Brightness
    and contrast are adjusted directly in RGB space, while saturation and hue are
    adjusted in HSV color space.

    Parameters
    ----------
    brightness_range : tuple[float, float], default=(0, 0.3)
        Range used to sample the brightness factor. The final factor is computed
        as ``1.0 + random.uniform(*brightness_range)``.
    contrast_range : tuple[float, float], default=(0, 0.3)
        Range used to sample the contrast factor. The final factor is computed
        as ``1.0 + random.uniform(*contrast_range)``.
    saturation_range : tuple[float, float], default=(0, 0.3)
        Range used to sample the saturation factor. The final factor is computed
        as ``1.0 + random.uniform(*saturation_range)``.
    hue_range : tuple[float, float], default=(0, 0.1)
        Range used to sample the hue shift. Values are interpreted as fractions
        of OpenCV's hue range, where hue values are in ``[0, 179]``.
    prob : float, default=1.0
        Probability of applying the transform.

    Notes
    -----
    The input image is expected to be an RGB image with pixel values in
    ``[0, 255]``. The returned image has dtype ``np.uint8``.
    """
    def __init__(
        self,
        brightness_range=(0, 0.3),
        contrast_range=(0, 0.3),
        saturation_range=(0, 0.3),
        hue_range=(0, 0.1),
        prob=1.0,
    ):
        super().__init__(prob)
        self.brightness_range = brightness_range
        self.contrast_range = contrast_range
        self.saturation_range = saturation_range
        self.hue_range = hue_range

    def apply(self, img: np.ndarray) -> np.ndarray:
        arr = img.astype(np.float32)

        # Brightness
        if self.brightness_range != (0, 0):
            factor = 1.0 + random.uniform(*self.brightness_range)
            arr = arr * factor

        # Contrast
        if self.contrast_range[1] > 0:
            factor = 1.0 + random.uniform(*self.contrast_range)
            mean = arr.mean(axis=(0, 1), keepdims=True)
            arr = (arr - mean) * factor + mean

        arr = np.clip(arr, 0, 255).astype(np.uint8)

        # Saturation / Hue
        if self.saturation_range[1] > 0 or self.hue_range[1] > 0:
            hsv = cv2.cvtColor(arr, cv2.COLOR_RGB2HSV).astype(np.float32)

            if self.saturation_range[1] > 0:
                factor = 1.0 + random.uniform(*self.saturation_range)
                hsv[..., 1] *= factor

            if self.hue_range[1] > 0:
                shift = random.uniform(
                    self.hue_range[0] * 179,
                    self.hue_range[1] * 179,
                )
                hsv[..., 0] = (hsv[..., 0] + shift) % 180

            hsv[..., 1:] = np.clip(hsv[..., 1:], 0, 255)
            hsv = hsv.astype(np.uint8)

            arr = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)

        return arr

RandomFlip

Bases: Transform

Randomly flip an image horizontally and/or vertically.

This transform independently applies horizontal and vertical flips with probability 1.0.

Parameters:

Name Type Description Default
prob float

Probability of applying the transform.

1.0
Notes

The returned array is made contiguous using np.ascontiguousarray.

Source code in src/histokit/augmentation/rotations.py
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class RandomFlip(Transform):
    """Randomly flip an image horizontally and/or vertically.

    This transform independently applies horizontal and vertical flips with
    probability ``1.0``.

    Parameters
    ----------
    prob : float, default=1.0
        Probability of applying the transform.

    Notes
    -----
    The returned array is made contiguous using ``np.ascontiguousarray``.
    """
    def __init__(self, prob=1.0):
        super().__init__(prob)

    def apply(self, img: np.ndarray) -> np.ndarray:
        """Apply random horizontal and vertical flips.

        Parameters
        ----------
        img : np.ndarray
            Input image with shape ``(H, W)`` or ``(H, W, C)``.

        Returns
        -------
        np.ndarray
            Flipped image with the same shape and dtype as ``img``.
        """
        if random.random() < self.prob:
            img = np.fliplr(img)

        if random.random() < self.prob:
            img = np.flipud(img)

        return np.ascontiguousarray(img)

apply

apply(img: ndarray) -> np.ndarray

Apply random horizontal and vertical flips.

Parameters:

Name Type Description Default
img ndarray

Input image with shape (H, W) or (H, W, C).

required

Returns:

Type Description
ndarray

Flipped image with the same shape and dtype as img.

Source code in src/histokit/augmentation/rotations.py
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
def apply(self, img: np.ndarray) -> np.ndarray:
    """Apply random horizontal and vertical flips.

    Parameters
    ----------
    img : np.ndarray
        Input image with shape ``(H, W)`` or ``(H, W, C)``.

    Returns
    -------
    np.ndarray
        Flipped image with the same shape and dtype as ``img``.
    """
    if random.random() < self.prob:
        img = np.fliplr(img)

    if random.random() < self.prob:
        img = np.flipud(img)

    return np.ascontiguousarray(img)

RandomRotation

Bases: Transform

Randomly rotate an image by 90-degree increments.

This transform rotates the input image by a random multiple of 90 degrees, selected from the set {0, 1, 2, 3}.

Parameters:

Name Type Description Default
prob float

Probability of applying the transform.

1.0
Notes

The returned array is made contiguous using np.ascontiguousarray.

Source code in src/histokit/augmentation/rotations.py
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
class RandomRotation(Transform):
    """Randomly rotate an image by 90-degree increments.

    This transform rotates the input image by a random multiple of 90 degrees,
    selected from the set {0, 1, 2, 3}.

    Parameters
    ----------
    prob : float, default=1.0
        Probability of applying the transform.

    Notes
    -----
    The returned array is made contiguous using ``np.ascontiguousarray``.
    """
    def __init__(self, prob=1.0):
        super().__init__(prob)

    def apply(self, img: np.ndarray) -> np.ndarray:
        """Apply a random 90-degree rotation.

        Parameters
        ----------
        img : np.ndarray
            Input image with shape ``(H, W)`` or ``(H, W, C)``.

        Returns
        -------
        np.ndarray
            Rotated image. The output has the same dtype as ``img``. Its shape
            may have swapped height and width when rotated by 90 or 270 degrees.
        """
        k = random.randint(0, 3)
        return np.ascontiguousarray(np.rot90(img, k))

apply

apply(img: ndarray) -> np.ndarray

Apply a random 90-degree rotation.

Parameters:

Name Type Description Default
img ndarray

Input image with shape (H, W) or (H, W, C).

required

Returns:

Type Description
ndarray

Rotated image. The output has the same dtype as img. Its shape may have swapped height and width when rotated by 90 or 270 degrees.

Source code in src/histokit/augmentation/rotations.py
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def apply(self, img: np.ndarray) -> np.ndarray:
    """Apply a random 90-degree rotation.

    Parameters
    ----------
    img : np.ndarray
        Input image with shape ``(H, W)`` or ``(H, W, C)``.

    Returns
    -------
    np.ndarray
        Rotated image. The output has the same dtype as ``img``. Its shape
        may have swapped height and width when rotated by 90 or 270 degrees.
    """
    k = random.randint(0, 3)
    return np.ascontiguousarray(np.rot90(img, k))

StainNormalizationTransform

Bases: Transform

Apply stain normalization as an augmentation transform.

This transform wraps a stain normalizer object and applies its transform method to the input image.

Parameters:

Name Type Description Default
normalizer object

Fitted stain normalizer object. The object is expected to implement a transform(img) method that accepts an RGB image as a NumPy array.

required
prob float

Probability of applying the transform.

1.0
Notes

If stain normalization fails, a warning is emitted and an empty white image with the same shape and dtype as the input image is returned.

Source code in src/histokit/augmentation/stain_normalization.py
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class StainNormalizationTransform(Transform):
    """Apply stain normalization as an augmentation transform.

    This transform wraps a stain normalizer object and applies its
    ``transform`` method to the input image.

    Parameters
    ----------
    normalizer : object
        Fitted stain normalizer object. The object is expected to implement
        a ``transform(img)`` method that accepts an RGB image as a NumPy array.
    prob : float, default=1.0
        Probability of applying the transform.

    Notes
    -----
    If stain normalization fails, a warning is emitted and an empty white image
    with the same shape and dtype as the input image is returned.
    """

    def __init__(self, normalizer, prob=1.0):
        super().__init__(prob)
        self.normalizer = normalizer

    def apply(self, img: np.ndarray) -> np.ndarray:
        """Apply stain normalization to an image.

        Parameters
        ----------
        img : np.ndarray
            Input RGB image with shape ``(H, W, 3)`` and pixel values usually
            in ``[0, 255]``.

        Returns
        -------
        np.ndarray
            Stain-normalized image. If normalization fails, returns a white
            image with the same shape and dtype as ``img``.

        Warns
        -----
        RuntimeWarning
            If the normalizer fails to transform the input image.
        """
        try:
            img_norm = self.normalizer.transform(img)
            return img_norm

        except Exception:
            warnings.warn(
                "Stain normalization failed. Returning an empty white image (255, 255, 255) "
                "This may be due to the image being too small, empty, or having "
                "very low contrast. Consider adjusting the parameters of the "
                "normalizer or using a different normalizer.",
                RuntimeWarning,
                stacklevel=2,
            )
            return np.ones_like(img) * 255

apply

apply(img: ndarray) -> np.ndarray

Apply stain normalization to an image.

Parameters:

Name Type Description Default
img ndarray

Input RGB image with shape (H, W, 3) and pixel values usually in [0, 255].

required

Returns:

Type Description
ndarray

Stain-normalized image. If normalization fails, returns a white image with the same shape and dtype as img.

Warns:

Type Description
RuntimeWarning

If the normalizer fails to transform the input image.

Source code in src/histokit/augmentation/stain_normalization.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def apply(self, img: np.ndarray) -> np.ndarray:
    """Apply stain normalization to an image.

    Parameters
    ----------
    img : np.ndarray
        Input RGB image with shape ``(H, W, 3)`` and pixel values usually
        in ``[0, 255]``.

    Returns
    -------
    np.ndarray
        Stain-normalized image. If normalization fails, returns a white
        image with the same shape and dtype as ``img``.

    Warns
    -----
    RuntimeWarning
        If the normalizer fails to transform the input image.
    """
    try:
        img_norm = self.normalizer.transform(img)
        return img_norm

    except Exception:
        warnings.warn(
            "Stain normalization failed. Returning an empty white image (255, 255, 255) "
            "This may be due to the image being too small, empty, or having "
            "very low contrast. Consider adjusting the parameters of the "
            "normalizer or using a different normalizer.",
            RuntimeWarning,
            stacklevel=2,
        )
        return np.ones_like(img) * 255

Cohort processing

cohort

__all__ module-attribute

__all__ = ['SlidesConfig', 'CohortConfig', 'StageConfig', 'LoggingConfig', 'SourceConfig', 'CohortLogger', 'CohortRunner']

SlidesConfig dataclass

Source code in src/histokit/cohort/config.py
 9
10
11
12
13
@dataclass
class SlidesConfig:
    input_dir: str
    file_list: str | list[str] | None = None
    pattern: str = "*.svs"

CohortConfig dataclass

Source code in src/histokit/cohort/config.py
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
@dataclass
class CohortConfig:
    slides: SlidesConfig
    output_dir: str = "./outputs"
    saver: str | None = "hdf5"
    logging: LoggingConfig | None = None

    tissue_detection: StageConfig | None = None
    artifact_detection: StageConfig | None = None
    statistics: StageConfig | None = None
    geojson: StageConfig | None = None

    @property
    def input_dir(self) -> str:
        return self.slides.input_dir

    @property
    def file_list(self) -> str | list[str] | None:
        return self.slides.file_list

    @property
    def pattern(self) -> str:
        return self.slides.pattern

    @classmethod
    def from_yaml(cls, path: str | Path) -> "CohortConfig":
        path = Path(path).resolve()

        with open(path, "r", encoding="utf-8") as fh:
            data = yaml.safe_load(fh) or {}

        config = cls.from_dict(data)

        config._resolve_paths(base_dir=path.parent)

        return config

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> "CohortConfig":
        data = data or {}

        slides = cls._build_slides_config(data.get("slides", {}))

        output_dir = data.get("output_dir", "./outputs")
        saver = data.get("saver", "hdf5")

        logging = cls._build_logging_config(
            data.get("logging", {}),
            output_dir=output_dir,
        )

        stages = data.get("stages", {}) or {}

        common_stage_kwargs = {
            "input_dir": slides.input_dir,
            "file_list": slides.file_list,
            "pattern": slides.pattern,
            "output_dir": output_dir,
            "saver": saver,
            "logging": logging,
        }

        tissue_detection = cls._build_stage_config(
            stages.get("tissue_detection"),
            stage_name="tissue_detection",
            **common_stage_kwargs,
        )

        artifact_detection = cls._build_stage_config(
            stages.get("artifact_detection"),
            stage_name="artifact_detection",
            **common_stage_kwargs,
        )

        statistics = cls._build_stage_config(
            stages.get("statistics"),
            stage_name="statistics",
            **common_stage_kwargs,
        )

        geojson = cls._build_stage_config(
            stages.get("geojson"),
            stage_name="geojson",
            **common_stage_kwargs,
        )

        return cls(
            slides=slides,
            output_dir=output_dir,
            saver=saver,
            logging=logging,
            tissue_detection=tissue_detection,
            artifact_detection=artifact_detection,
            statistics=statistics,
            geojson=geojson
        )

    @staticmethod
    def _build_slides_config(data: dict[str, Any]) -> SlidesConfig:
        data = data or {}

        return SlidesConfig(
            input_dir=data.get("input_dir", "./data/slides"),
            file_list=data.get("file_list"),
            pattern=data.get("pattern", "*.svs"),
        )

    @staticmethod
    def _build_logging_config(
        data: dict[str, Any],
        output_dir: str,
    ) -> LoggingConfig:
        data = data or {}

        return LoggingConfig(
            enabled=data.get("enabled", True),
            log_dir=data.get("log_dir", str(Path(output_dir) / "logs")),
            processed_file=data.get("processed_file", "processed.csv"),
            errors_file=data.get("errors_file", "errors.csv"),
        )

    @classmethod
    def _build_stage_config(
        cls,
        data: dict[str, Any] | None,
        stage_name: str,
        input_dir: str,
        file_list: str | list[str] | None,
        pattern: str,
        output_dir: str,
        saver: str | None,
        logging: LoggingConfig,
    ) -> StageConfig | None:
        if data is None:
            return None

        data = data or {}

        stage_name = data.get("stage_name", stage_name)
        enabled = data.get("enabled", True)

        if not enabled:
            return None

        tissue_source = cls._build_source_config(data.get("tissue_source"))
        artifact_source = cls._build_source_config(data.get("artifact_source"))

        parallel_workers = data.get(
            "parallel_workers",
            data.get("workers", 1),
        )

        return StageConfig(
            stage_name=stage_name,
            enabled=enabled,
            algorithm=data.get("algorithm"),
            mag_l0=data.get("mag_l0", None),
            config_path=data.get("config_path"),
            parallel_workers=parallel_workers,
            overwrite=data.get("overwrite", False),
            tissue_source=tissue_source,
            artifact_source=artifact_source,
            input_dir=input_dir,
            file_list=file_list,
            pattern=pattern,
            output_dir=output_dir,
            saver=saver,
            logging=logging,
        )

    @staticmethod
    def _build_source_config(
        data: dict[str, Any] | None,
    ) -> SourceConfig | None:
        if data is None:
            return None

        if isinstance(data, SourceConfig):
            return data

        dir = data.get("dir")

        if dir is None:
            raise ValueError(
                f"Source config must contain 'dir'. Got: {data}"
            )

        return SourceConfig(
            dir=dir,
        )

    def _resolve_paths(self, base_dir: Path) -> None:
        self.slides.input_dir = str(self._resolve_path(self.slides.input_dir, base_dir))
        self.output_dir = str(self._resolve_path(self.output_dir, base_dir))

        if self.logging is not None and self.logging.log_dir is not None:
            self.logging.log_dir = str(self._resolve_path(self.logging.log_dir, base_dir))

        for stage in [
            self.tissue_detection,
            self.artifact_detection,
            self.statistics,
            self.geojson,
        ]:
            if stage is None:
                continue

            stage.input_dir = self.slides.input_dir
            stage.output_dir = self.output_dir

            if stage.config_path is not None:
                stage.config_path = str(self._resolve_path(stage.config_path, base_dir))

            if stage.logging is not None and stage.logging.log_dir is not None:
                stage.logging.log_dir = str(
                    self._resolve_path(stage.logging.log_dir, base_dir)
                )

    @staticmethod
    def _resolve_path(path: str | Path, base_dir: Path) -> Path:
        path = Path(path)

        if path.is_absolute():
            return path

        return base_dir / path

StageConfig dataclass

Source code in src/histokit/cohort/config.py
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
@dataclass
class StageConfig:
    enabled: bool = True

    stage_name: str = "stage"

    algorithm: str | None = None
    config_path: str | None = None

    mag_l0: float | None = None

    parallel_workers: int = 1
    overwrite: bool = False

    tissue_source: SourceConfig | None = None
    artifact_source: SourceConfig | None = None

    input_dir: str = "./data/slides"
    file_list: str | list[str] | None = None
    pattern: str = "*.svs"

    output_dir: str = "./outputs"
    saver: str | None = "hdf5"

    logging: LoggingConfig | None = None

LoggingConfig dataclass

Source code in src/histokit/cohort/config.py
17
18
19
20
21
22
@dataclass
class LoggingConfig:
    enabled: bool = True
    log_dir: str | None = None
    processed_file: str = "processed.csv"
    errors_file: str = "errors.csv"

SourceConfig dataclass

Source code in src/histokit/cohort/config.py
25
26
27
@dataclass
class SourceConfig:
    dir: str

CohortLogger

Source code in src/histokit/cohort/logger.py
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class CohortLogger:
    def __init__(self, log_dir):
        self.log_dir = Path(log_dir)
        self.log_dir.mkdir(parents=True, exist_ok=True)

        self.processed_path = self.log_dir / "processed.csv"
        self.errors_path = self.log_dir / "errors.csv"

        self._init_file(
            self.processed_path,
            ["stage", "slide_path", "basename", "status", "time"],
        )

        self._init_file(
            self.errors_path,
            ["stage", "slide_path", "basename", "error", "traceback"],
        )

    def _init_file(self, path, header):
        if not path.exists():
            with open(path, "w", newline="", encoding="utf-8") as f:
                csv.writer(f).writerow(header)

    def log_processed(self, stage, slide_path, basename, elapsed):
        with open(self.processed_path, "a", newline="", encoding="utf-8") as f:
            csv.writer(f).writerow(
                [stage, str(slide_path), basename, "success", elapsed]
            )

    def log_error(self, stage, slide_path, basename, error):
        with open(self.errors_path, "a", newline="", encoding="utf-8") as f:
            csv.writer(f).writerow(
                [
                    stage,
                    str(slide_path),
                    basename,
                    repr(error),
                    traceback.format_exc(),
                ]
            )

CohortRunner

Source code in src/histokit/cohort/runner.py
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
class CohortRunner:
    def __init__(self, config: CohortConfig):
        self.config = config
        self.logger = logging.getLogger(__name__)

        logging.basicConfig(
            level=logging.INFO,
            format="%(asctime)s - %(message)s",
        )

    def run(self):
        if self.config.tissue_detection is not None:
            self.logger.info("Running tissue segmentation pipeline...")
            tissue_pipeline = TissueSegmentationPipeline(self.config.tissue_detection)
            tissue_pipeline.run()
            tissue_src = tissue_pipeline.result_dir()

        if self.config.artifact_detection is not None:
            self.logger.info("=> Running artifact segmentation pipeline...")
            artifact_pipeline = ArtifactSegmentationPipeline(
                self.config.artifact_detection
            )

            artifact_pipeline.set_tissue_src_from_pipeline(tissue_src)
            artifact_pipeline.run()
            art_src = artifact_pipeline.result_dir()


        if self.config.statistics is not None:
            self.logger.info("=> Calculating statistics...")
            stats = StatsPipeline(self.config.statistics)
            #stats.set_art_src_from_pipeline(art_src)
            stats.run()

        if self.config.geojson is not None:
            self.logger.info("=> Converting to geojson...")

            geojson = GeojsonPipeline(self.config.geojson)
            #geojson.set_art_src_from_pipeline(art_src)
            geojson.run()

    @staticmethod
    def load_grid_search_config(path_or_dict):
        if isinstance(path_or_dict, (str, Path)):
            with open(path_or_dict, "r", encoding="utf-8") as f:
                return yaml.safe_load(f) or {}

        return path_or_dict or {}

    @staticmethod
    def iter_param_combinations(params: dict):
        keys = list(params.keys())

        values = [
            value if isinstance(value, list) else [value]
            for value in params.values()
        ]

        for combination in product(*values):
            yield dict(zip(keys, combination))

    def iter_grid_cases(self, grid_config: dict):
        for case in grid_config.get("cases", []):
            case_name = case["name"]
            params = case.get("params", {})

            for combination in self.iter_param_combinations(params):
                yield case_name, combination

    @staticmethod
    def safe_name(value):
        text = str(value).replace(".", "p")
        text = re.sub(r"[^a-zA-Z0-9_-]+", "_", text)
        return text

    def make_run_name(self, params: dict):
        return "__".join(
            f"{key}_{self.safe_name(value)}"
            for key, value in params.items()
        )

    def run_grid_search(self, param_grid: dict | str | Path):
        param_grid = self.load_grid_search_config(param_grid)

        if self.config.tissue_detection is not None:
            print("=> Running tissue detection ...")
            print(f"Input directory: {self.config.input_dir}")
            print(f"Output directory: {self.config.output_dir}")

            tissue_pipeline = TissueSegmentationPipeline(self.config.tissue_detection)
            tissue_pipeline.run()

        if self.config.artifact_detection is not None:
            artifact_grid = param_grid.get("artifact_detection", {})
            artifact_stage_config = deepcopy(self.config.artifact_detection)


            with open(Path(artifact_stage_config.config_path), "r", encoding="utf-8") as f:
                base_grandqc_config = yaml.safe_load(f)

            for case_name, params in self.iter_grid_cases(artifact_grid):
                grandqc_config = deepcopy(base_grandqc_config)
                stage_config = deepcopy(artifact_stage_config)

                for param, value in params.items():
                    grandqc_config[param] = value

                if grandqc_config.get("blending_mode") == "constant":
                    grandqc_config.pop("blending_sigma", None)

                run_name = self.make_run_name(params)

                output_dir = (
                    Path(self.config.output_dir)
                    / "grid_search"
                    / run_name
                )   

                output_dir.mkdir(parents=True, exist_ok=True)
                stage_config.output_dir = str(output_dir)

                temp_config_path = output_dir / "grandqc_grid_config.yaml"

                with open(temp_config_path, "w", encoding="utf-8") as f:
                    yaml.safe_dump(grandqc_config, f, sort_keys=False)

                stage_config.config_path = str(temp_config_path)

                print("")
                print(f"=> Running artifact detection grid search: {case_name}")
                print(f"Parameters: {params}")

                artifact_pipeline = ArtifactSegmentationPipeline(stage_config)
                artifact_pipeline.run()

Patch Extraction

patch_extractors

__all__ module-attribute

__all__ = ['ParallelExtractor', 'PatchImageWriter']

ParallelExtractor

Source code in src/histokit/patch_extractors/parallel_extractor.py
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
class ParallelExtractor:
    def __init__(
        self,
        patch_size: int = 512,
        prep_fn=None,
        aug_fn=None,
        exclude_fn=None,
        mask_loader=HDF5Saver(),
        extraction_strategy=None,
        extract_mag: float = 5,
        pad_value: int = 255,
        save_patches: bool = False,
    ):
        self.patch_size = patch_size
        self.prep_fn = prep_fn
        self.aug_fn = aug_fn
        self.exclude_fn = exclude_fn
        self.mask_loader = mask_loader
        self.extract_mag = extract_mag
        self.pad_value = pad_value
        self.save_patches = save_patches

        self.extraction_strategy = extraction_strategy or GridExtractionStrategy()

    def extract_patches(
        self,
        slide_path,
        path_mask=None,
        out_dir=None,
        batch_size: int = 16,
        num_workers: int = 4,
        pin_memory: bool = True,
    ):
        slide = Slide(slide_path)
        basename = Path(slide_path).stem

        if path_mask is not None:
            mask_data = self.mask_loader.load(path_mask)
        else:
            w, h = slide.get_size_at_mag(self.extract_mag)
            mask_data = {
                "mask": None,
                "bbox": [np.array([0, 0, w, h])],
                "mag_save": self.extract_mag
            }

        if self.save_patches:
            if out_dir is None:
                raise ValueError("out_dir must be provided when save_patches=True")

            out_dir = Path(out_dir)
            out_dir.mkdir(exist_ok=True)

        for obj_idx, (mask, bbox) in enumerate(
            zip(mask_data["mask"], mask_data["bbox"])
        ):

            mask[mask!=255] = 0
            region = slide.read_masked_object(
                bbox = bbox,
                mask = mask,
                mag_bbox=mask_data["mag_save"],
                mag=self.extract_mag,
                pad_value=self.pad_value,
            )

            region_np = np.asarray(region)

            patch_writer = None
            if self.save_patches:
                patch_writer = PatchImageWriter(
                    out_dir=out_dir,
                    prefix=f"{basename}_R{obj_idx}",
                )

            ds = self.extraction_strategy.build_dataset(
                region_np=region_np,
                bbox_list=[bbox],
                patch_size=self.patch_size,
                pad_value=self.pad_value,
                exclude_fn=self.exclude_fn,
                prep_fn=self.prep_fn,
                aug_fn=self.aug_fn,
                patch_writer=patch_writer,
            )

            dataloader = DataLoader(
                ds,
                batch_size=batch_size,
                shuffle=False,
                num_workers=num_workers,
                collate_fn=self.collate_remove_none,
                pin_memory=pin_memory,
            )

            for batch in dataloader:
                if batch is None:
                    continue
                yield batch


    @staticmethod
    def collate_remove_none(batch):
        batch = [b for b in batch if b is not None]

        if len(batch) == 0:
            return None

        return default_collate(batch)

PatchImageWriter

Source code in src/histokit/patch_extractors/patch_writer.py
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class PatchImageWriter:
    def __init__(self, out_dir, prefix="patch"):
        self.out_dir = Path(out_dir)
        self.out_dir.mkdir(parents=True, exist_ok=True)
        self.prefix = prefix

    def __call__(self, patch, x_start, y_start, x_end, y_end, exclude=False):
        if exclude:
            return  # Skip writing excluded patches
        filename = f"{self.prefix}_{x_start}_{y_start}_{x_end}_{y_end}.png"
        print(f"Writing {filename}")
        Image.fromarray(patch).save(self.out_dir / filename)