from bioMONAI.core import cells3d, img2Tensor
from bioMONAI.visualize import visualize_slices
Transforms
Size & Sampling
Resample
Resample (sampling, **kwargs)
A subclass of Spacing that handles image resampling based on specified sampling factors or voxel dimensions.
The Resample
class inherits from Spacing
and provides a flexible way to adjust the spacing (voxel size) of images by specifying either a sampling factor or explicitly providing new voxel dimensions.
Details | |
---|---|
sampling | Sampling factor for isotropic resampling |
kwargs |
= BioImageStack(img2Tensor(cells3d()[:,0]))
img =False)
visualize_slices(img, showlines
= Resample(4)(img)
img2 =False) visualize_slices(img2, showlines
Resize
Resize (size=None, **kwargs)
A subclass of Reshape that handles image resizing based on specified target dimensions.
The Resize
class inherits from Reshape
and provides a flexible way to adjust the size of images by specifying either a target size or scaling factors.
Type | Default | Details | |
---|---|---|---|
size | NoneType | None | Target dimensions for resizing (height, width). If its length is smaller than the spatial dimensions, values will be repeated. If an int is provided, it will be broadcast to all spatial dimensions. |
kwargs |
print(img.size())
=False)
visualize_slices(img, showlines
= Resize(50)(img)
img2 print(img2.size())
=False) visualize_slices(img2, showlines
torch.Size([60, 256, 256])
torch.Size([60, 50, 50])
CropND
CropND (slices:list, dims:list=None)
Crops an ND tensor along a specified dimension.
This transform crops an ND tensor along specified dimensions, which could be a channel or spatial dimension.
Type | Default | Details | |
---|---|---|---|
slices | list | List of slice objects or tuples (start, end) for each dimension | |
dims | list | None | List of dimensions to apply the slices. If None, slices are applied to all dimensions. |
# Define the slices for cropping
= [(30, 50)]
slices
# Create an instance of CropND
= CropND(slices=slices)
crop_transform
= crop_transform(img)
img3 print(img3.size())
=False) visualize_slices(img3, showlines
torch.Size([20, 256, 256])
# Define the slices for cropping
= [(30, 50), (0, 40)]
slices = [0, 2]
dims # Create an instance of CropND
= CropND(slices=slices, dims=dims)
crop_transform
= crop_transform(img)
img3 print(img3.size())
=False) visualize_slices(img3, showlines
torch.Size([20, 256, 40])
Noise
RandCameraNoise
RandCameraNoise (p:float=1.0, damp=0.01, qe=0.7, gain=2, offset=100, exp_time=0.1, dark_current=0.6, readout=1.5, bitdepth=16, seed=42, simulation=False, camera='cmos', gain_variance=0.1, offset_variance=5)
Simulates camera noise by adding Poisson shot noise, dark current noise, and optionally CMOS fixed pattern noise.
Returns: numpy.ndarray: The noisy image as a NumPy array with dimensions of input_image.
Type | Default | Details | |
---|---|---|---|
p | float | 1.0 | Probability of applying Transform |
damp | float | 0.01 | Dampening factor to prevent saturation when adding noise |
qe | float | 0.7 | Quantum efficiency of the camera (0 to 1). |
gain | int | 2 | Camera gain factor. If an array, it should be broadcastable with input_image shape. |
offset | int | 100 | Camera offset in ADU. If an array, it should be broadcastable with input_image shape. |
exp_time | float | 0.1 | Exposure time in seconds. |
dark_current | float | 0.6 | Dark current per pixel in electrons/second. |
readout | float | 1.5 | Readout noise standard deviation in electrons. |
bitdepth | int | 16 | Bit depth of the camera output. |
seed | int | 42 | Seed for random number generator for reproducibility. |
simulation | bool | False | If True, assumes input_image is already in units of photons and does not convert from electrons. |
camera | str | cmos | Specifies the type of camera (‘cmos’ or any other). Used to add CMOS fixed pattern noise if ‘cmos’ is specified. |
gain_variance | float | 0.1 | Variance for the gain noise in CMOS cameras. Only applicable if camera type is ‘cmos’. |
offset_variance | int | 5 | Variance for the offset noise in CMOS cameras. Only applicable if camera type is ‘cmos’. |
from bioMONAI.visualize import plot_image
= img[30] img3
# Original clean image
plot_image(img3)
# Noisy image simulating a CMOS camera
= 'cmos').encodes(img3)) plot_image(RandCameraNoise(camera
# Noisy image simulating a CCD camera
= 'ccd', readout=2).encodes(img3)) plot_image(RandCameraNoise(camera
Blur
Blur (sigma=1.0, ksize=5, prob=0.5)
Apply Gaussian blur to the image.
# Generate a random NumPy array
= np.random.rand(64, 64)
random_array # Apply Blur transform to the image
= Blur(ksize=15, prob=1)
blur_transform = blur_transform(random_array)
blurred_nparray
# plot the original image
plot_image(random_array)# Plot the blurred image
plot_image(blurred_nparray)
# Apply Blur transform to the image
= Blur(sigma=5, prob=1.0)
blur_transform = blur_transform(img)
blurred_img
# plot the original image
plot_image(img)# Plot the blurred image
plot_image(blurred_img)
Normalization
ScaleIntensity
ScaleIntensity (x, min=0.0, max=1.0, axis=None, eps=1e-20, dtype=<class 'numpy.float32'>)
Image normalization.
Type | Default | Details | |
---|---|---|---|
x | The input image to scale. | ||
min | float | 0.0 | The minimum intensity value. |
max | float | 1.0 | The maximum intensity value. |
axis | NoneType | None | The axis or axes along which to compute the minimum and maximum values. |
eps | float | 1e-20 | A small value to prevent division by zero. |
dtype | type | float32 | The data type to use for the output image. |
ScaleIntensityPercentiles
ScaleIntensityPercentiles (x, pmin=3, pmax=99.8, axis=None, clip=True, b_min=0.0, b_max=1.0, eps=1e-20, dtype=<class 'numpy.float32'>)
Percentile-based image normalization.
Type | Default | Details | |
---|---|---|---|
x | The input image to scale. | ||
pmin | int | 3 | The minimum percentile value. |
pmax | float | 99.8 | The maximum percentile value. |
axis | NoneType | None | The axis or axes along which to compute the minimum and maximum values. |
clip | bool | True | If True, clips the output values to the specified range. |
b_min | float | 0.0 | The minimum intensity value. |
b_max | float | 1.0 | The maximum intensity value. |
eps | float | 1e-20 | A small value to prevent division by zero. |
dtype | type | float32 | The data type to use for the output image. |
ScaleIntensityVariance
ScaleIntensityVariance (target_variance=1.0, ndim=2)
Scales the intensity variance of an ND image to a target value.
Type | Default | Details | |
---|---|---|---|
target_variance | float | 1.0 | The desired variance for the scaled intensities. |
ndim | int | 2 | Number of spatial dimensions in the image. |
# Example usage with a random tensor of shape (1, 3, 256, 256)
= BioImageBase(torch.rand(1, 3, 256, 256))
rand_tensor
= ScaleIntensityVariance(ndim=4)
transform
# Apply the transform to the tensor
= transform(rand_tensor)
scaled_tensor
print('Original Tensor Variance:', rand_tensor.var().item())
print('Scaled Tensor Variance:', scaled_tensor.var().item())
Original Tensor Variance: 0.08313275873661041
Scaled Tensor Variance: 0.9999999403953552
Data Augmentation
RandCrop2D
RandCrop2D (size:int|tuple, lazy=False, **kwargs)
Randomly crops a 2D image to a specified size.
This transform randomly crops a 2D image to a specified size during training and performs a center crop during validation.
Type | Default | Details | |
---|---|---|---|
size | int | tuple | Size to crop to, duplicated if one value is specified | |
lazy | bool | False | a flag to indicate whether this transform should execute lazily or not. Defaults to False |
kwargs |
RandCropND
RandCropND (size:int|tuple, lazy=False, **kwargs)
Randomly crops an ND image to a specified size.
This transform randomly crops an ND image to a specified size during training and performs a center crop during validation. It supports both 2D and 3D images and videos, assuming the first dimension is the batch dimension.
Type | Default | Details | |
---|---|---|---|
size | int | tuple | Size to crop to, duplicated if one value is specified | |
lazy | bool | False | a flag to indicate whether this transform should execute lazily or not. Defaults to False |
kwargs |
# Define a random tensor
= (65, 65)
orig_size = BioImageBase(torch.rand(8, *orig_size))
rand_tensor
for i in range(100):
8,64,64),RandCropND((64,64))(rand_tensor).shape) test_eq((
RandFlip
RandFlip (prob=0.1, spatial_axis=None, ndim=2, lazy=False, **kwargs)
Randomly flips an ND image over a specified axis. Works with both NumPy arrays and BioImageBase objects.
Type | Default | Details | |
---|---|---|---|
prob | float | 0.1 | Probability of flipping |
spatial_axis | NoneType | None | Axes to flip. Default is None (random selection) |
ndim | int | 2 | Number of spatial dimensions |
lazy | bool | False | Flag for lazy execution (for BioImageBase) |
kwargs |
= np.random.rand(1, 3, 3)
image = RandFlip(prob=1., ndim=2, spatial_axis=1)
flip_transform = flip_transform(image)
flipped_image print('original:\n', image)
print('flipped:\n', flipped_image)
0,0,0], flipped_image[0,2,0]) # Check if the image is flipped correctly test_eq(image[
original:
[[[0.19383875 0.06490635 0.53667235]
[0.09049494 0.73128362 0.34212699]
[0.11334854 0.94422553 0.07012528]]]
flipped:
[[[0.11334854 0.94422553 0.07012528]
[0.09049494 0.73128362 0.34212699]
[0.19383875 0.06490635 0.53667235]]]
# Define a random tensor
= (1,4,4)
orig_size = BioImageBase(torch.rand(*orig_size))
rand_tensor print('orig tensor: ', rand_tensor, '\n')
for i in range(3):
print(RandFlip(prob=.75, spatial_axis=None)(rand_tensor))
orig tensor: metatensor([[[0.1672, 0.4126, 0.7319, 0.0511],
[0.7415, 0.0333, 0.8199, 0.3043],
[0.3868, 0.0628, 0.4574, 0.7334],
[0.2620, 0.6334, 0.8148, 0.4110]]])
metatensor([[[0.0511, 0.7319, 0.4126, 0.1672],
[0.3043, 0.8199, 0.0333, 0.7415],
[0.7334, 0.4574, 0.0628, 0.3868],
[0.4110, 0.8148, 0.6334, 0.2620]]])
metatensor([[[0.2620, 0.6334, 0.8148, 0.4110],
[0.3868, 0.0628, 0.4574, 0.7334],
[0.7415, 0.0333, 0.8199, 0.3043],
[0.1672, 0.4126, 0.7319, 0.0511]]])
metatensor([[[0.4110, 0.8148, 0.6334, 0.2620],
[0.7334, 0.4574, 0.0628, 0.3868],
[0.3043, 0.8199, 0.0333, 0.7415],
[0.0511, 0.7319, 0.4126, 0.1672]]])
RandRot90
RandRot90 (prob=0.1, k=1, max_k=3, spatial_axes=(0, 1), ndim=2, lazy=False, **kwargs)
Randomly rotate an ND image by 90 degrees in the plane specified by axes.
Type | Default | Details | |
---|---|---|---|
prob | float | 0.1 | Probability of rotating |
k | int | 1 | Number of times to rotate by 90 degrees. If k is None, it will be set randomly in before_call . |
max_k | int | 3 | Max number of times to rotate by 90 degrees |
spatial_axes | tuple | (0, 1) | Spatial axes that define the plane around which to rotate. Default: (0, 1), this are the first two axis in spatial dimensions. |
ndim | int | 2 | Number of spatial dimensions |
lazy | bool | False | Flag to indicate whether this transform should execute lazily or not. Defaults to False |
kwargs |
# Define a random tensor
= (1,4,4)
orig_size = BioImageBase(torch.rand(*orig_size))
rand_tensor
print('orig tensor: ', rand_tensor, '\n')
for i in range(3):
print(RandRot90(prob=1, k=i+1)(rand_tensor))
orig tensor: metatensor([[[0.7716, 0.6624, 0.6430, 0.2887],
[0.8335, 0.5942, 0.8943, 0.4312],
[0.9377, 0.4562, 0.4537, 0.2435],
[0.6081, 0.1670, 0.9703, 0.6659]]])
metatensor([[[0.2887, 0.4312, 0.2435, 0.6659],
[0.6430, 0.8943, 0.4537, 0.9703],
[0.6624, 0.5942, 0.4562, 0.1670],
[0.7716, 0.8335, 0.9377, 0.6081]]])
metatensor([[[0.6659, 0.9703, 0.1670, 0.6081],
[0.2435, 0.4537, 0.4562, 0.9377],
[0.4312, 0.8943, 0.5942, 0.8335],
[0.2887, 0.6430, 0.6624, 0.7716]]])
metatensor([[[0.6081, 0.9377, 0.8335, 0.7716],
[0.1670, 0.4562, 0.5942, 0.6624],
[0.9703, 0.4537, 0.8943, 0.6430],
[0.6659, 0.2435, 0.4312, 0.2887]]])