Operations on volumetric data
The qim3d library provides a set of methods for different operations on volumes.
Operations on volumes.
qim3d.operations.remove_background
remove_background(
volume,
median_filter_size=2,
min_object_radius=3,
background='dark',
**median_kwargs,
)
Applies a background correction pipeline using median filtering and morphological operations.
This function acts as a convenience wrapper for a sequential processing pipeline designed to smooth the image and suppress clutter. It performs two distinct operations:
- Median Filter: Reduces high-frequency impulse noise (salt-and-pepper) using a kernel of size
median_filter_size. - Morphological Opening: Removes bright features (or dark, if
background='bright') that are smaller than themin_object_radius. This effectively separates large structural components from small background artifacts or texture.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
volume
|
ndarray
|
The input volume to process. |
required |
median_filter_size
|
int
|
The size of the kernel for the initial median denoising step. Defaults to 2. |
2
|
min_object_radius
|
int
|
The radius of the structuring element (ball) used for the morphological operation. Details smaller than this size are removed. Defaults to 3. |
3
|
background
|
str
|
The intensity of the background relative to the objects.
|
'dark'
|
**median_kwargs
|
Any
|
Additional keyword arguments passed to the underlying |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
filtered_volume |
ndarray
|
The processed volume with background clutter and noise suppressed. |
Example
import qim3d
vol = qim3d.examples.cement_128x128x128
fig1 = qim3d.viz.slices_grid(vol, value_min=0, value_max=255, num_slices=5, display_figure=True)
vol_filtered = qim3d.operations.remove_background(vol,
min_object_radius=3,
background="bright")
fig2 = qim3d.viz.slices_grid(vol_filtered, value_min=0, value_max=255, num_slices=5, display_figure=True)
Source code in qim3d/operations/_common_operations_methods.py
qim3d.operations.fade_mask
fade_mask(
volume,
decay_rate=10,
ratio=0.5,
geometry='spherical',
invert=False,
axis=0,
**kwargs,
)
Applies a soft attenuation mask (vignetting) to the volume to suppress boundary artifacts.
This function multiplies the input volume by a generated mask that decays from the center outwards based on a power-law profile. It is commonly used to remove reconstruction artifacts at the edges of a scan or to isolate a central Region of Interest (ROI) by suppressing peripheral data. The shape of the mask can be spherical or cylindrical.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
volume
|
ndarray
|
The 3D input volume. |
required |
decay_rate
|
float
|
The exponent for the power-law decay. Higher values create a "flatter" central region with a sharper drop-off near the mask edge, while lower values cause a more gradual fade from the center. Defaults to 10. |
10
|
ratio
|
float
|
The effective radius of the non-zero mask region relative to the volume size. Defaults to 0.5. |
0.5
|
geometry
|
str
|
The geometric shape of the mask.
|
'spherical'
|
invert
|
bool
|
If |
False
|
axis
|
int
|
The axis of alignment for the cylinder if |
0
|
**kwargs
|
Any
|
Additional keyword arguments. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
faded_vol |
ndarray
|
The volume with the attenuation mask applied, renormalized to match the original maximum intensity. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Example
Image before edge fading has visible artifacts, which obscures the object of interest. Afterwards the artifacts are faded out, making the object of interest more visible for visualization purposes.Source code in qim3d/operations/_common_operations_methods.py
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 | |
qim3d.operations.overlay_rgb_images
Composites a foreground image onto a background using alpha blending.
This function overlays a mask or secondary image (foreground) onto a base image (background). It automatically normalizes inputs (handling 2D/3D, float/integer, and range mismatches) to ensure compatible 8-bit RGB formats before blending. A key feature is the conditional transparency (hide_black), which treats black pixels in the foreground as fully transparent, making it ideal for overlaying sparse segmentation masks without obscuring the rest of the image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
background
|
ndarray
|
The base image. |
required |
foreground
|
ndarray
|
The overlay image (e.g., a segmentation mask or heatmap). Must match the spatial dimensions of the background. |
required |
alpha
|
float
|
The global opacity of the foreground, ranging from 0.0 (fully transparent) to 1.0 (fully opaque). Defaults to 0.5. |
0.5
|
hide_black
|
bool
|
If |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
composite |
ndarray
|
The resulting 8-bit RGB image after blending. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the spatial dimensions (height/width) of the input images do not match. |
Source code in qim3d/operations/_common_operations_methods.py
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 | |
qim3d.operations.make_hollow
Constructs a hollow shell from a solid 3D volume.
This function isolates the outer boundary layer of an object. It achieves this by performing a morphological erosion (using a minimum filter) to identify the inner core, which is then subtracted from the original volume via a logical XOR operation. The result is a shell that retains the original intensity values, while the interior is set to zero.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
volume
|
ndarray
|
The input 3D volume. Non-zero values are treated as the object. |
required |
thickness
|
int
|
The width of the resulting shell in voxels. This value determines the size of the erosion kernel used to define the hollow core. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
vol_hollowed |
ndarray
|
The processed volume containing only the outer shell of the object. |
Example
import qim3d
# Generate volume and visualize it
vol = qim3d.generate.volume(noise_scale = 0.01)
qim3d.viz.slicer(vol)
# Hollow volume and visualize it
vol_hollowed = qim3d.operations.make_hollow(vol, thickness=10)
qim3d.viz.slicer(vol_hollowed)
Source code in qim3d/operations/_common_operations_methods.py
qim3d.operations.pad
Symmetrically pads a 3D volume with zeros (zero-padding).
This function increases the dimensions of the volume by adding empty space (zeros) around the original data. It is commonly used to prepare data for neural network inputs (to match required input sizes), prevent boundary artifacts during convolution, or center an object within a larger field of view.
The padding amount is applied to each side of the axis. For example, x_axis=10 adds 10 pixels to the left and 10 pixels to the right, increasing the total width by 20.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
volume
|
ndarray
|
The input 3D volume (Z, Y, X). |
required |
x_axis
|
float
|
Pixels to add to each side of the X dimension (width). Can be an integer or half-integer (e.g., 2.5 adds 2 pixels to one side and 3 to the other). Defaults to 0. |
0
|
y_axis
|
float
|
Pixels to add to each side of the Y dimension (height). Defaults to 0. |
0
|
z_axis
|
float
|
Pixels to add to each side of the Z dimension (depth). Defaults to 0. |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
padded_volume |
ndarray
|
The resized volume containing the centered original data. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the input volume is not 3D or if padding values are negative. |
Example
(100, 100, 100) (100, 120, 120)Source code in qim3d/operations/_volume_operations.py
qim3d.operations.pad_to
Pads the input volume with zeros to match a specific target shape.
This function centers the original volume within a larger array of size shape. It is useful for standardizing image sizes in a dataset (e.g., for machine learning models that require fixed input dimensions) without resizing or interpolating the data.
If a target dimension is smaller than the original volume dimension, padding is skipped for that axis (the volume is not cropped).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
volume
|
ndarray
|
The input 3D volume. |
required |
shape
|
tuple[int, int, int]
|
The desired output shape |
required |
Returns:
| Name | Type | Description |
|---|---|---|
padded_volume |
ndarray
|
The volume padded to the specified dimensions. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the input volume or target shape is not 3D, or if |
Example
(100, 100, 100) (110, 110, 110)Source code in qim3d/operations/_volume_operations.py
qim3d.operations.trim
Crops the volume to the bounding box of the non-zero content.
This function removes all "empty" (all-zero) planes from the borders of the 3D volume. It effectively shrinks the array to the smallest cuboid that still contains all the data, discarding the surrounding background. This is useful for reducing memory usage and file size after applying a mask or ROI.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
volume
|
ndarray
|
The 3D input volume. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
trimmed_volume |
ndarray
|
The cropped volume containing only the region with non-zero values. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the input |
Example
(100, 100, 100) (80, 80, 80)Source code in qim3d/operations/_volume_operations.py
qim3d.operations.shear3d
shear3d(
volume,
x_shift_y=0,
x_shift_z=0,
y_shift_x=0,
y_shift_z=0,
z_shift_x=0,
z_shift_y=0,
order=1,
)
Applies a geometric shear transformation to distort the 3D volume.
This function displaces voxels along one axis based on their position along another axis. It essentially "slides" the slices of the volume relative to each other. This is useful for data augmentation (creating variations for training) or correcting geometric distortions (e.g., deskewing data acquired from a misaligned stage).
The shift parameters define the maximum displacement in pixels. The shift is applied linearly from -shift at one end of the axis to +shift at the other, resulting in a total range of 2 * shift.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
volume
|
ndarray
|
The input 3D volume (Z, Y, X). |
required |
x_shift_y
|
int
|
Max shift in X, varying along the Y-axis. Defaults to 0. |
0
|
x_shift_z
|
int
|
Max shift in X, varying along the Z-axis. Defaults to 0. |
0
|
y_shift_x
|
int
|
Max shift in Y, varying along the X-axis. Defaults to 0. |
0
|
y_shift_z
|
int
|
Max shift in Y, varying along the Z-axis. Defaults to 0. |
0
|
z_shift_x
|
int
|
Max shift in Z, varying along the X-axis. Defaults to 0. |
0
|
z_shift_y
|
int
|
Max shift in Z, varying along the Y-axis. Defaults to 0. |
0
|
order
|
int
|
The order of the spline interpolation used during resampling.
|
1
|
Returns:
| Name | Type | Description |
|---|---|---|
sheared_volume |
ndarray
|
The deformed volume. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the input is not 3D, |
Example
import qim3d
import numpy as np
# Generate box for shearing
vol = np.zeros((60,100,100))
vol[:, 20:80, 20:80] = 1
qim3d.viz.slicer(vol, slice_axis=1)
# Shear the volume by 20% factor in x-direction along z-axis
factor = 0.2
shift = int(vol.shape[0]*factor)
sheared_vol = qim3d.operations.shear3d(vol, x_shift_z=shift, order=1)
qim3d.viz.slicer(sheared_vol, slice_axis=1)
Source code in qim3d/operations/_volume_operations.py
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 | |
qim3d.operations.curve_warp
curve_warp(
volume,
x_amp=0,
y_amp=0,
x_periods=1.0,
y_periods=1.0,
x_offset=0.0,
y_offset=0.0,
order=1,
)
Applies a sinusoidal geometric distortion (warping) to the 3D volume along the Z-axis.
This function displaces voxels in the X and/or Y directions based on their position along the Z-axis, following a sine wave pattern. This creates a "wavy" or "snake-like" deformation through the depth of the volume. It is primarily used for data augmentation to simulate non-rigid deformations or acquisition artifacts in training data.
The displacement is calculated as:
delta_x(z) = x_amp * sin(2 * pi * x_periods * (z / depth) + x_offset)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
volume
|
ndarray
|
The input 3D volume (Z, Y, X). |
required |
x_amp
|
float
|
The amplitude of the sine wave in the X-direction. Defines the maximum shift in pixels. Defaults to 0. |
0
|
y_amp
|
float
|
The amplitude of the sine wave in the Y-direction. Defaults to 0. |
0
|
x_periods
|
float
|
The frequency of the wave. Represents the number of full sine wave cycles that occur along the full length of the Z-axis. Defaults to 1.0. |
1.0
|
y_periods
|
float
|
The frequency of the wave in the Y-direction. Defaults to 1.0. |
1.0
|
x_offset
|
float
|
The phase shift or starting position of the wave in the X-direction (in radians). Defaults to 0.0. |
0.0
|
y_offset
|
float
|
The phase shift in the Y-direction. Defaults to 0.0. |
0.0
|
order
|
int
|
The order of the spline interpolation used during resampling.
|
1
|
Returns:
| Name | Type | Description |
|---|---|---|
warped_volume |
ndarray
|
The distorted volume. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the input volume is not 3D or if |
Example
import qim3d
import numpy as np
# Generate box for warping
vol = np.zeros((100,100,100))
vol[:,40:60, 40:60] = 1
qim3d.viz.slicer(vol, slice_axis=1)
# Warp the box along the x dimension
warped_volume = qim3d.operations.curve_warp(vol, x_amp=10, x_periods=4)
qim3d.viz.slicer(warped_volume, slice_axis=1)
Source code in qim3d/operations/_volume_operations.py
279 280 281 282 283 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 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 | |
qim3d.operations.stretch
Resizes (stretches or compresses) the volume along one or more axes using interpolation.
This function changes the aspect ratio and spatial resolution of the volume by resampling it onto a new grid.
- Positive stretch: Increases the size of the volume (upsampling). The content appears elongated.
- Negative stretch: Decreases the size of the volume (downsampling). The content appears compressed.
The operation is "symmetric" in terms of the input parameter: a stretch of N adds (or removes) N pixels to both ends of the axis, changing the total dimension by 2 * N.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
volume
|
ndarray
|
The input 3D volume (Z, Y, X). |
required |
x_stretch
|
int
|
Pixels added/removed per side along the X-axis. Total width changes by |
0
|
y_stretch
|
int
|
Pixels added/removed per side along the Y-axis. Defaults to 0. |
0
|
z_stretch
|
int
|
Pixels added/removed per side along the Z-axis. Defaults to 0. |
0
|
order
|
int
|
The order of spline interpolation.
|
1
|
Returns:
| Name | Type | Description |
|---|---|---|
stretched_volume |
ndarray
|
The resized volume. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the input volume is not 3D, |
Example
import qim3d
import numpy as np
# Generate box for stretching
vol = np.zeros((100,100,100))
vol[:,20:80, 20:80] = 1
qim3d.viz.slicer(vol)
# Stretch the box along the x dimension
stretched_volume = qim3d.operations.stretch(vol, x_stretch=20)
print(stretched_volume.shape)
qim3d.viz.slicer(stretched_volume)
# Squeeze the box along the y dimension
squeezed_volume = qim3d.operations.stretch(vol, x_stretch=-20)
print(squeezed_volume.shape)
qim3d.viz.slicer(squeezed_volume)

Source code in qim3d/operations/_volume_operations.py
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 | |
qim3d.operations.center_twist
Applies a geometric twist transformation to the volume around a central axis.
This function progressively rotates the slices of the volume along the specified axis, creating a spiral or screw-like distortion. The rotation angle increases linearly from 0 degrees at the start of the axis to rotation_angle at the end. This is often used for data augmentation to simulate torsional deformation in biological samples or materials.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
volume
|
ndarray
|
The input 3D volume (Z, Y, X). |
required |
rotation_angle
|
float
|
The total rotation in degrees applied from the bottom to the top of the axis. Defaults to 90. |
90
|
axis
|
str
|
The axis of rotation.
|
'z'
|
order
|
int
|
The order of spline interpolation used during resampling.
|
1
|
Returns:
| Name | Type | Description |
|---|---|---|
twisted_volume |
ndarray
|
The distorted volume. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the input volume is not 3D, |
Example
Source code in qim3d/operations/_volume_operations.py
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 | |
qim3d.operations.get_random_slice
Extracts an arbitrary 2D plane (slice) from the 3D volume at a random orientation and position.
This function samples a rectangular region from the volume by defining a random plane vector and origin point. It effectively acts as a "virtual camera" placed inside the volume at a random angle. This is particularly useful for data augmentation in machine learning, allowing a model to see the 3D structure from diverse angles rather than just the fixed orthogonal (XY, XZ, YZ) views.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
volume
|
ndarray
|
The input 3D volume. |
required |
width
|
int
|
The width of the extracted slice in pixels. |
required |
length
|
int
|
The length (height) of the extracted slice in pixels. |
required |
seed
|
int
|
A seed for the random number generator. Providing a value ensures that the same random slice can be reproduced. Defaults to |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
slice2d |
ndarray
|
The extracted 2D image of shape |
Reference
This slicer is adapted from the interactive-unet package developed by William Laprade.
Example
random_slices = []
for i in range(15):
random_slices.append(qim3d.operations.get_random_slice(vol, width=100, length=100))
qim3d.viz.slices_grid(np.array(random_slices))
Source code in qim3d/operations/_slicing_operations.py
qim3d.operations.subsample
Reduces the volume resolution by extracting every N'th voxel (strided slicing).
This function performs downsampling by selecting voxels at regular intervals defined by the coarseness factor. It is highly efficient because it returns a view of the original array rather than a copy. This means it consumes almost no additional memory, making it ideal for generating quick previews, thumbnails, or testing pipelines on large datasets without full processing.
Important notice
Since the returned object is a view, modifying the subsampled volume will also modify the original input volume.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
volume
|
ndarray
|
The input 3D volume. |
required |
coarseness
|
int or list[int]
|
The step size (stride) for sampling.
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
subsampled_volume |
ndarray
|
A view of the input volume with reduced dimensions. |
Example
import qim3d
import numpy as np
# Create a sample volume
vol = np.zeros((100, 100, 100))
# Subsample by taking every 4th voxel
vol_small = qim3d.operations.subsample(vol, coarseness=4)
print(f"Original shape: {vol.shape}")
print(f"Subsampled shape: {vol_small.shape}")
Subsampled shape: (25, 25, 25)
Source code in qim3d/operations/_slicing_operations.py
qim3d.operations.ratio_subsample
Subsamples the volume to retain a specific fraction of the original data.
This function automatically calculates the integer stride (step size) required to reduce the volume's total element count to approximately the requested ratio. Like subsample, it returns a view of the original array, making it extremely memory-efficient and fast for creating lightweight previews or managing large datasets.
Note: The exact ratio may not be achievable because the stride must be an integer. The function selects the stride that results in a size closest to the target.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
volume
|
ndarray
|
The input 3D volume. |
required |
ratio
|
float
|
The target fraction of elements to keep, where 0 < ratio <= 1. For example, |
required |
Returns:
| Name | Type | Description |
|---|---|---|
subsampled_volume |
ndarray
|
A view of the input volume with reduced dimensions. |
Example
import qim3d
import numpy as np
# Create a volume with 1 million voxels
vol = np.zeros((100, 100, 100))
# Subsample to keep ~1.5% of the data
# Ideally, stride = cbrt(1/0.015) ≈ 4.05 -> stride 4
vol_small = qim3d.operations.ratio_subsample(vol, ratio=0.015)
print(f"Original size: {vol.size}")
print(f"Subsampled size: {vol_small.size}")
print(f"Actual ratio: {vol_small.size / vol.size:.4f}")
Original size: 1000000
Subsampled size: 15625
Actual ratio: 0.0156
Source code in qim3d/operations/_slicing_operations.py
Morphological operations for volumetric data.
qim3d.morphology.dilate
Performs morphological dilation on a 3D volume using CPU or GPU-accelerated methods.
Dilation enlarges bright regions (foreground) and shrinks dark regions (background). It is commonly used to close small holes, connect disjoint features, or thicken object boundaries.
This function supports efficient GPU acceleration using the pygorpho library, based on zonohedral approximations. If a GPU is not available, it is recommended to use the 'scipy.ndimage' method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
volume
|
ndarray
|
The input 3D volume. |
required |
kernel
|
int or ndarray
|
The structuring element. * If method is 'pygorpho.linear': Must be an integer representing the radius of the ball-shaped kernel. * If method is 'pygorpho.flat' or 'scipy.ndimage': Must be a 3D numpy array defining the footprint. |
required |
method
|
str
|
The backend implementation to use. Defaults to 'pygorpho.linear'. * 'pygorpho.linear': GPU-accelerated. Best for large, spherical kernels. * 'pygorpho.flat': GPU-accelerated. Supports arbitrary kernel shapes. * 'scipy.ndimage': CPU-based. Standard implementation (slower for large volumes). |
'pygorpho.linear'
|
**kwargs
|
Any
|
Additional keyword arguments passed to the underlying method. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
dilated_vol |
ndarray
|
The dilated volume. |
Reference
The GPU methods implement the algorithms described in: Zonohedral Approximation of Spherical Structuring Element for Volumetric Morphology.
Example
Source code in qim3d/morphology/_common_morphologies.py
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 | |
qim3d.morphology.erode
Performs morphological erosion on a 3D volume using CPU or GPU-accelerated methods.
Erosion shrinks bright regions (foreground) and enlarges dark regions (background). It is commonly used to remove small noise (salt noise), detach touching objects, or thin out features.
This function supports efficient GPU acceleration using the pygorpho library. If a GPU is not available, it is recommended to use the 'scipy.ndimage' method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
volume
|
ndarray
|
The input 3D volume. |
required |
kernel
|
int or ndarray
|
The structuring element. * If method is 'pygorpho.linear': Must be an integer representing the radius of the ball-shaped kernel. * If method is 'pygorpho.flat' or 'scipy.ndimage': Must be a 3D numpy array defining the footprint. |
required |
method
|
str
|
The backend implementation to use. Defaults to 'pygorpho.linear'. * 'pygorpho.linear': GPU-accelerated. Best for large, spherical kernels. * 'pygorpho.flat': GPU-accelerated. Supports arbitrary kernel shapes. * 'scipy.ndimage': CPU-based. Standard implementation (slower for large volumes). |
'pygorpho.linear'
|
**kwargs
|
Any
|
Additional keyword arguments passed to the underlying method. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
eroded_vol |
ndarray
|
The eroded volume. |
Reference
The GPU methods implement the algorithms described in: Zonohedral Approximation of Spherical Structuring Element for Volumetric Morphology.
Example
Source code in qim3d/morphology/_common_morphologies.py
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 | |
qim3d.morphology.opening
Performs morphological opening on a 3D volume using CPU or GPU-accelerated methods.
Opening is defined as an erosion followed by a dilation. It is primarily used to remove small bright objects (salt noise) from the background while preserving the shape and size of larger objects. It smooths object contours by breaking narrow isthmuses and eliminating thin protrusions.
This function supports efficient GPU acceleration using the pygorpho library. If a GPU is not available, it is recommended to use the scipy.ndimage method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
volume
|
ndarray
|
The input 3D volume. |
required |
kernel
|
int or ndarray
|
The structuring element. * If method is 'pygorpho.linear': Must be an integer representing the radius of the ball-shaped kernel. * If method is 'pygorpho.flat' or 'scipy.ndimage': Must be a 3D numpy array defining the footprint. |
required |
method
|
str
|
The backend implementation to use. Defaults to 'pygorpho.linear'. * 'pygorpho.linear': GPU-accelerated. Best for large, spherical kernels. * 'pygorpho.flat': GPU-accelerated. Supports arbitrary kernel shapes. * 'scipy.ndimage': CPU-based. Standard implementation (slower for large volumes). |
'pygorpho.linear'
|
**kwargs
|
Any
|
Additional keyword arguments passed to the underlying method. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
opened_vol |
ndarray
|
The opened volume. |
Reference
The GPU methods implement the algorithms described in: Zonohedral Approximation of Spherical Structuring Element for Volumetric Morphology.
Example
import qim3d
import numpy as np
# Generate tubular synthetic blob
vol = qim3d.generate.volume(noise_scale=0.025, seed=50)
# Add noise to the data
vol_noised = qim3d.generate.background(
background_shape=vol.shape,
apply_method = 'add',
apply_to = vol
)
# Visualize synthetic volume
qim3d.viz.volumetric(vol_noised, grid_visible=True)
Source code in qim3d/morphology/_common_morphologies.py
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 283 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 337 338 339 | |
qim3d.morphology.closing
Performs morphological closing on a 3D volume using CPU or GPU-accelerated methods.
Closing is defined as a dilation followed by an erosion. It is primarily used to fill small dark holes, cracks, or gaps within bright objects while preserving their overall shape and size. It smooths object contours by fusing narrow breaks and filling small depressions.
This function supports efficient GPU acceleration using the pygorpho library. If a GPU is not available, it is recommended to use the scipy.ndimage method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
volume
|
ndarray
|
The input 3D volume. |
required |
kernel
|
int or ndarray
|
The structuring element. * If method is 'pygorpho.linear': Must be an integer representing the radius of the ball-shaped kernel. * If method is 'pygorpho.flat' or 'scipy.ndimage': Must be a 3D numpy array defining the footprint. |
required |
method
|
str
|
The backend implementation to use. Defaults to 'pygorpho.linear'. * 'pygorpho.linear': GPU-accelerated. Best for large, spherical kernels. * 'pygorpho.flat': GPU-accelerated. Supports arbitrary kernel shapes. * 'scipy.ndimage': CPU-based. Standard implementation (slower for large volumes). |
'pygorpho.linear'
|
**kwargs
|
Any
|
Additional keyword arguments passed to the underlying method. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
closed_vol |
ndarray
|
The closed volume. |
Reference
The GPU methods implement the algorithms described in: Zonohedral Approximation of Spherical Structuring Element for Volumetric Morphology.
Example
Source code in qim3d/morphology/_common_morphologies.py
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 | |
qim3d.morphology.black_tophat
Performs the black top-hat transform on a 3D volume.
The black top-hat transform is defined as the difference between the morphological closing of the volume and the original volume (Closing - Input). It is used to extract dark features and valleys that are smaller than the structuring element (kernel) from a brighter background. This is particularly effective for background correction or isolating small dark structures in a non-uniformly lit image.
This function supports efficient GPU acceleration using the pygorpho library. If a GPU is not available, it is recommended to use the scipy.ndimage method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
volume
|
ndarray
|
The input 3D volume. |
required |
kernel
|
int or ndarray
|
The structuring element. * If method is 'pygorpho.linear': Must be an integer representing the radius of the ball-shaped kernel. * If method is 'pygorpho.flat' or 'scipy.ndimage': Must be a 3D numpy array defining the footprint. |
required |
method
|
str
|
The backend implementation to use. Defaults to 'pygorpho.linear'. * 'pygorpho.linear': GPU-accelerated. Best for large, spherical kernels. * 'pygorpho.flat': GPU-accelerated. Supports arbitrary kernel shapes. * 'scipy.ndimage': CPU-based. Standard implementation (slower for large volumes). |
'pygorpho.linear'
|
**kwargs
|
Any
|
Additional keyword arguments passed to the underlying method. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
bothat_vol |
ndarray
|
The processed volume containing the extracted dark features. |
Reference
The GPU methods implement the algorithms described in: Zonohedral Approximation of Spherical Structuring Element for Volumetric Morphology.
Example
Source code in qim3d/morphology/_common_morphologies.py
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 | |
qim3d.morphology.white_tophat
Performs the white top-hat transform on a 3D volume.
The white top-hat transform is defined as the difference between the original volume and its morphological opening (Input - Opening). It is used to extract bright features and peaks that are smaller than the structuring element (kernel) from a darker background. This is a powerful tool for background subtraction, enhancing small bright spots, or correcting uneven illumination in a volume.
This function supports efficient GPU acceleration using the pygorpho library. If a GPU is not available, it is recommended to use the scipy.ndimage method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
volume
|
ndarray
|
The input 3D volume. |
required |
kernel
|
int or ndarray
|
The structuring element. * If method is 'pygorpho.linear': Must be an integer representing the radius of the ball-shaped kernel. * If method is 'pygorpho.flat' or 'scipy.ndimage': Must be a 3D numpy array defining the footprint. |
required |
method
|
str
|
The backend implementation to use. Defaults to 'pygorpho.linear'. * 'pygorpho.linear': GPU-accelerated. Best for large, spherical kernels. * 'pygorpho.flat': GPU-accelerated. Supports arbitrary kernel shapes. * 'scipy.ndimage': CPU-based. Standard implementation (slower for large volumes). |
'pygorpho.linear'
|
**kwargs
|
Any
|
Additional keyword arguments passed to the underlying method. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
tophat_vol |
ndarray
|
The processed volume containing the extracted bright features. |
Reference
The GPU methods implement the algorithms described in: Zonohedral Approximation of Spherical Structuring Element for Volumetric Morphology.
Example
Source code in qim3d/morphology/_common_morphologies.py
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 | |