|
1 | 1 | """Functions to work with ImageJ label images.""" |
2 | 2 |
|
3 | | -from ij import IJ, ImagePlus, Prefs |
| 3 | +from ij import IJ, ImagePlus, Prefs, ImageStack |
4 | 4 | from ij.plugin import Duplicator, ImageCalculator |
5 | 5 | from ij.plugin.filter import ImageProcessor, ThresholdToSelection |
6 | 6 | from ij.process import FloatProcessor, ImageProcessor |
@@ -182,3 +182,52 @@ def binary_to_label(imp, title, min_thresh=1, min_vol=None, max_vol=None): |
182 | 182 | seg.setTitle(title) |
183 | 183 |
|
184 | 184 | return seg.getImagePlus() |
| 185 | + |
| 186 | + |
| 187 | +def dilate_labels_2d(imp, dilation_radius): |
| 188 | + """ |
| 189 | + Dilate each label in the given ImagePlus using the specified dilation radius. |
| 190 | +
|
| 191 | + Parameters |
| 192 | + ---------- |
| 193 | + imp : ij.ImagePlus |
| 194 | + Input ImagePlus with the labels to dilate |
| 195 | + dilation_radius : int |
| 196 | + Number of pixels to dilate each label |
| 197 | +
|
| 198 | + Returns |
| 199 | + ------- |
| 200 | + ij.ImagePlus |
| 201 | + New ImagePlus with the dilated labels |
| 202 | + """ |
| 203 | + |
| 204 | + # Create a list of the dilated labels |
| 205 | + dilated_labels_list = [] |
| 206 | + |
| 207 | + # Iterate over each slice of the input ImagePlus |
| 208 | + for i in range(1, imp.getNSlices() + 1): |
| 209 | + # Duplicate the current slice |
| 210 | + current_imp = Duplicator().run(imp, 1, 1, i, imp.getNSlices(), 1, 1) |
| 211 | + |
| 212 | + # Perform a dilation of the labels in the current slice |
| 213 | + IJ.run( |
| 214 | + current_imp, |
| 215 | + "Label Morphological Filters", |
| 216 | + "operation=Dilation radius=" + str(dilation_radius) + " from_any_label", |
| 217 | + ) |
| 218 | + |
| 219 | + # Get the dilated labels |
| 220 | + dilated_labels_imp = IJ.getImage() |
| 221 | + |
| 222 | + # Hide the dilated labels to avoid visual clutter |
| 223 | + dilated_labels_imp.hide() |
| 224 | + |
| 225 | + # Append the dilated labels to the list |
| 226 | + dilated_labels_list.append(dilated_labels_imp) |
| 227 | + |
| 228 | + # Create a new ImagePlus with the dilated labels |
| 229 | + dilated_labels_imp = ImagePlus( |
| 230 | + "Dilated labels", ImageStack().create(dilated_labels_list) |
| 231 | + ) |
| 232 | + |
| 233 | + return dilated_labels_imp |
0 commit comments