Skip to content

napari_cellseg3d.code_models.crf

Implements the CRF post-processing step for WNet3D.

The CRF requires the following parameters:

  • images : Array of shape (N, C, H, W, D) containing the input images.
  • predictions: Array of shape (N, K, H, W, D) containing the predicted class probabilities for each pixel.
  • sa: alpha standard deviation, the scale of the spatial part of the appearance/bilateral kernel.
  • sb: beta standard deviation, the scale of the color part of the appearance/bilateral kernel.
  • sg: gamma standard deviation, the scale of the smoothness/gaussian kernel.
  • w1: weight of the appearance/bilateral kernel.
  • w2: weight of the smoothness/gaussian kernel.

Inspired by https://arxiv.org/abs/1606.00915 and https://arxiv.org/abs/1711.08506. Also uses research from: Efficient Inference in Fully Connected CRFs with Gaussian Edge Potentials Philipp Krähenbühl and Vladlen Koltun NIPS 2011

Implemented using the pydensecrf library available at https://github.com/lucasb-eyer/pydensecrf. However, this is not maintained, thus we maintain this pacakge at https://github.com/AdaptiveMotorControlLab/pydensecrf.

Classes:

Name Description
CRFWorker

Worker for the CRF post-processing step for the WNet3D.

Functions:

Name Description
correct_shape_for_crf

Corrects the shape of the image to be compatible with the CRF post-processing step.

crf

Implements the CRF post-processing step for the WNet3D.

crf_batch

CRF post-processing step for the WNet3D, applied to a batch of images.

crf_with_config

Implements the CRF post-processing step for the WNet3D.

CRFWorker

Bases: GeneratorWorker

Worker for the CRF post-processing step for the WNet3D.

Methods:

Name Description
__init__

Initializes the CRFWorker.

Source code in napari_cellseg3d/code_models/crf.py
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
class CRFWorker(GeneratorWorker):
    """Worker for the CRF post-processing step for the WNet3D."""

    def __init__(
        self,
        images_list: list,
        labels_list: list,
        config: CRFConfig = None,
        log=None,
    ):
        """Initializes the CRFWorker.

        Args:
            images_list (list): List of images to process.
            labels_list (list): List of labels to process.
            config (CRFConfig, optional): Configuration for the CRF post-processing step. Defaults to None.
            log (function, optional): Logging function. Defaults to None.
        """
        super().__init__(self._run_crf_job)

        self.images = images_list
        self.labels = labels_list
        if config is None:
            self.config = CRFConfig()
        else:
            self.config = config
        self.log = log

    def _run_crf_job(self):
        """Runs the CRF post-processing step for the WNet3D."""
        if not CRF_INSTALLED:
            logger.info(
                "pydensecrf not installed, therefore CRF post-processing will not be available! Please install the package. "
                "Please install by running: pip install pydensecrf2 "
            )

        if len(self.images) != len(self.labels):
            raise ValueError("Number of images and labels must be the same.")

        for i in range(len(self.images)):
            if self.images[i].shape[-3:] != self.labels[i].shape[-3:]:
                raise ValueError("Image and labels must have the same shape.")

            im = correct_shape_for_crf(self.images[i])
            prob = correct_shape_for_crf(self.labels[i])

            logger.debug(f"image shape : {im.shape}")
            logger.debug(f"labels shape : {prob.shape}")

            yield crf(
                im,
                prob,
                self.config.sa,
                self.config.sb,
                self.config.sg,
                self.config.w1,
                self.config.w2,
                n_iter=self.config.n_iters,
            )

__init__

__init__(images_list: list, labels_list: list, config: CRFConfig = None, log=None)

Initializes the CRFWorker.

Parameters:

Name Type Description Default
images_list list

List of images to process.

required
labels_list list

List of labels to process.

required
config CRFConfig

Configuration for the CRF post-processing step. Defaults to None.

None
log function

Logging function. Defaults to None.

None
Source code in napari_cellseg3d/code_models/crf.py
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
def __init__(
    self,
    images_list: list,
    labels_list: list,
    config: CRFConfig = None,
    log=None,
):
    """Initializes the CRFWorker.

    Args:
        images_list (list): List of images to process.
        labels_list (list): List of labels to process.
        config (CRFConfig, optional): Configuration for the CRF post-processing step. Defaults to None.
        log (function, optional): Logging function. Defaults to None.
    """
    super().__init__(self._run_crf_job)

    self.images = images_list
    self.labels = labels_list
    if config is None:
        self.config = CRFConfig()
    else:
        self.config = config
    self.log = log

correct_shape_for_crf

correct_shape_for_crf(image, desired_dims=4)

Corrects the shape of the image to be compatible with the CRF post-processing step.

Source code in napari_cellseg3d/code_models/crf.py
42
43
44
45
46
47
48
49
50
51
def correct_shape_for_crf(image, desired_dims=4):
    """Corrects the shape of the image to be compatible with the CRF post-processing step."""
    logger.debug(f"Correcting shape for CRF, desired_dims={desired_dims}")
    logger.debug(f"Image shape: {image.shape}")
    if len(image.shape) > desired_dims:
        image = np.squeeze(image, axis=0)
    elif len(image.shape) < desired_dims:
        image = np.expand_dims(image, axis=0)
    logger.debug(f"Corrected image shape: {image.shape}")
    return image

crf

crf(image, prob, sa, sb, sg, w1, w2, n_iter=5)

Implements the CRF post-processing step for the WNet3D.

Inspired by https://arxiv.org/abs/1210.5644, https://arxiv.org/abs/1606.00915 and https://arxiv.org/abs/1711.08506. Implemented using the pydensecrf library.

Parameters:

Name Type Description Default
image ndarray

Array of shape (C, H, W, D) containing the input image.

required
prob ndarray

Array of shape (K, H, W, D) containing the predicted class probabilities for each pixel.

required
sa float

alpha standard deviation, the scale of the spatial part of the appearance/bilateral kernel.

required
sb float

beta standard deviation, the scale of the color part of the appearance/bilateral kernel.

required
sg float

gamma standard deviation, the scale of the smoothness/gaussian kernel.

required
w1 float

weight of the appearance/bilateral kernel.

required
w2 float

weight of the smoothness/gaussian kernel.

required
n_iter int

Number of iterations for the CRF post-processing step. Defaults to 5.

5

Returns:

Type Description

np.ndarray: Array of shape (K, H, W, D) containing the refined class probabilities for each pixel.

Source code in napari_cellseg3d/code_models/crf.py
 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
def crf(image, prob, sa, sb, sg, w1, w2, n_iter=5):
    """Implements the CRF post-processing step for the WNet3D.

    Inspired by https://arxiv.org/abs/1210.5644, https://arxiv.org/abs/1606.00915 and https://arxiv.org/abs/1711.08506.
    Implemented using the pydensecrf library.

    Args:
        image (np.ndarray): Array of shape (C, H, W, D) containing the input image.
        prob (np.ndarray): Array of shape (K, H, W, D) containing the predicted class probabilities for each pixel.
        sa (float): alpha standard deviation, the scale of the spatial part of the appearance/bilateral kernel.
        sb (float): beta standard deviation, the scale of the color part of the appearance/bilateral kernel.
        sg (float): gamma standard deviation, the scale of the smoothness/gaussian kernel.
        w1 (float): weight of the appearance/bilateral kernel.
        w2 (float): weight of the smoothness/gaussian kernel.
        n_iter (int, optional): Number of iterations for the CRF post-processing step. Defaults to 5.

    Returns:
        np.ndarray: Array of shape (K, H, W, D) containing the refined class probabilities for each pixel.
    """
    if not CRF_INSTALLED:
        logger.info(
            "pydensecrf not installed, therefore CRF post-processing will not be available! Please install the package. "
            "Please install by running: pip install pydensecrf2 "
        )
        return None

    d = dcrf.DenseCRF(image.shape[1] * image.shape[2] * image.shape[3], prob.shape[0])

    # Get unary potentials from softmax probabilities
    U = unary_from_softmax(prob)
    d.setUnaryEnergy(U)

    # Generate pairwise potentials
    featsGaussian = create_pairwise_gaussian(
        sdims=(sg, sg, sg), shape=image.shape[1:]
    )  # image.shape)
    featsBilateral = create_pairwise_bilateral(
        sdims=(sa, sa, sa),
        schan=tuple([sb for i in range(image.shape[0])]),
        img=image,
        chdim=-1,
    )

    # Add pairwise potentials to the CRF
    compat = np.ones(prob.shape[0], dtype=np.float32) - np.diag(
        [1 for i in range(prob.shape[0])]
        # , dtype=np.float32
    )
    d.addPairwiseEnergy(featsGaussian, compat=compat.astype(np.float32) * w2)
    d.addPairwiseEnergy(featsBilateral, compat=compat.astype(np.float32) * w1)

    # Run inference
    Q = d.inference(n_iter)

    return np.array(Q).reshape(
        (prob.shape[0], image.shape[1], image.shape[2], image.shape[3])
    )

crf_batch

crf_batch(images, probs, sa, sb, sg, w1, w2, n_iter=5)

CRF post-processing step for the WNet3D, applied to a batch of images.

Parameters:

Name Type Description Default
images ndarray

Array of shape (N, C, H, W, D) containing the input images.

required
probs ndarray

Array of shape (N, K, H, W, D) containing the predicted class probabilities for each pixel.

required
sa float

alpha standard deviation, the scale of the spatial part of the appearance/bilateral kernel.

required
sb float

beta standard deviation, the scale of the color part of the appearance/bilateral kernel.

required
sg float

gamma standard deviation, the scale of the smoothness/gaussian kernel.

required
w1 float

weight of the appearance/bilateral kernel.

required
w2 float

weight of the smoothness/gaussian kernel.

required
n_iter int

Number of iterations for the CRF post-processing step. Defaults to 5.

5

Returns:

Type Description

np.ndarray: Array of shape (N, K, H, W, D) containing the refined class probabilities for each pixel.

Source code in napari_cellseg3d/code_models/crf.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
def crf_batch(images, probs, sa, sb, sg, w1, w2, n_iter=5):
    """CRF post-processing step for the WNet3D, applied to a batch of images.

    Args:
        images (np.ndarray): Array of shape (N, C, H, W, D) containing the input images.
        probs (np.ndarray): Array of shape (N, K, H, W, D) containing the predicted class probabilities for each pixel.
        sa (float): alpha standard deviation, the scale of the spatial part of the appearance/bilateral kernel.
        sb (float): beta standard deviation, the scale of the color part of the appearance/bilateral kernel.
        sg (float): gamma standard deviation, the scale of the smoothness/gaussian kernel.
        w1 (float): weight of the appearance/bilateral kernel.
        w2 (float): weight of the smoothness/gaussian kernel.
        n_iter (int, optional): Number of iterations for the CRF post-processing step. Defaults to 5.

    Returns:
        np.ndarray: Array of shape (N, K, H, W, D) containing the refined class probabilities for each pixel.
    """
    if not CRF_INSTALLED:
        return None

    return np.stack(
        [
            crf(images[i], probs[i], sa, sb, sg, w1, w2, n_iter=n_iter)
            for i in range(images.shape[0])
        ],
        axis=0,
    )

crf_with_config

crf_with_config(image, prob, config: CRFConfig = None, log=logger.info)

Implements the CRF post-processing step for the WNet3D.

Parameters:

Name Type Description Default
image ndarray

Array of shape (C, H, W, D) containing the input image.

required
prob ndarray

Array of shape (K, H, W, D) containing the predicted class probabilities for each pixel.

required
config CRFConfig

Configuration for the CRF post-processing step. Defaults to None.

None
log function

Logging function. Defaults to logger.info.

info
Source code in napari_cellseg3d/code_models/crf.py
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
def crf_with_config(image, prob, config: CRFConfig = None, log=logger.info):
    """Implements the CRF post-processing step for the WNet3D.

    Args:
        image (np.ndarray): Array of shape (C, H, W, D) containing the input image.
        prob (np.ndarray): Array of shape (K, H, W, D) containing the predicted class probabilities for each pixel.
        config (CRFConfig, optional): Configuration for the CRF post-processing step. Defaults to None.
        log (function, optional): Logging function. Defaults to logger.info.
    """
    if config is None:
        config = CRFConfig()
    if image.shape[-3:] != prob.shape[-3:]:
        raise ValueError(
            f"Image and probability shapes do not match: {image.shape} vs {prob.shape}"
            f" (expected {image.shape[-3:]} == {prob.shape[-3:]})"
        )

    image = correct_shape_for_crf(image)
    prob = correct_shape_for_crf(prob)

    if log is not None:
        log("Running CRF post-processing step")
        log(f"Image shape : {image.shape}")
        log(f"Labels shape : {prob.shape}")

    return crf(
        image,
        prob,
        config.sa,
        config.sb,
        config.sg,
        config.w1,
        config.w2,
        config.n_iters,
    )