Skip to content
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/imgtools/transforms/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from .intensity_transforms import (
ClipIntensity,
IntensityTransform,
N4BiasFieldCorrection,
WindowIntensity,
)
from .lambda_transforms import ImageFunction, SimpleITKFilter
Expand Down Expand Up @@ -42,6 +43,7 @@
"IntensityTransform",
"ClipIntensity",
"WindowIntensity",
"N4BiasFieldCorrection",
# spatial transform
"SpatialTransform",
"Resample",
Expand Down
21 changes: 21 additions & 0 deletions src/imgtools/transforms/functional.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import numpy as np
import SimpleITK as sitk

from .lambda_transforms import SimpleITKFilter

INTERPOLATORS = {
"linear": sitk.sitkLinear,
"nearest": sitk.sitkNearestNeighbor,
Expand All @@ -13,6 +15,7 @@
"zoom",
"rotate",
"crop",
"bias_correction",
"clip_intensity",
"window_intensity",
]
Expand Down Expand Up @@ -410,3 +413,21 @@ def window_intensity(
lower = level - window / 2
upper = level + window / 2
return clip_intensity(image, lower, upper)


def bias_correction(image: sitk.Image) -> sitk.Image:
"""Apply N4 bias field correction to reduce smooth intensity inhomogeneities (bias fields) commonly found in
MR imaging. This transform corrects voxel intensities while preserving image geometry (spacing, orientation, and dimensions).

Parameters
----------
image : sitk.Image
The MR image to apply bias field correction to.

Returns
-------
sitk.Image
The bias corrected image
"""
bias_filter = SimpleITKFilter(sitk.N4BiasFieldCorrectionImageFilter())
return bias_filter(image)
45 changes: 41 additions & 4 deletions src/imgtools/transforms/intensity_transforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,13 @@
from SimpleITK import Image

from .base_transform import BaseTransform
from .functional import (
clip_intensity,
window_intensity,
)
from .functional import bias_correction, clip_intensity, window_intensity

__all__ = [
"IntensityTransform",
"ClipIntensity",
"WindowIntensity",
"N4BiasFieldCorrection",
]


Expand Down Expand Up @@ -150,3 +148,42 @@ def __call__(self, image: Image) -> Image:
"""

return window_intensity(image, self.window, self.level)


@dataclass
class N4BiasFieldCorrection(IntensityTransform):
"""N4BiasFieldCorrection operation class.

A callable class that applies N4 bias field correction to reduce
smooth intensity inhomogeneities (bias fields) commonly found in
MR imaging. This transform corrects voxel intensities while
preserving image geometry (spacing, orientation, and dimensions).

The correction uses SimpleITK's N4BiasFieldCorrectionImageFilter,
which implements the N4 algorithm (Tustison et al., 2010).

Notes
-----
- This transform is computationally intensive and may take several
seconds to minutes depending on image size.
- Best suited for MR images; application to other modalities is
typically not meaningful.
- No rotation, translation, or scaling is applied.
"""

# def __post_init__(self) -> None:
# self.filter = SimpleITKFilter(N4BiasFieldCorrectionImageFilter())

Comment on lines +174 to +176
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

Remove commented-out code.

This commented-out __post_init__ block is dead code. If it's no longer needed, it should be removed to keep the codebase clean. If it's a placeholder for future work, consider opening an issue to track it instead.

-    # def __post_init__(self) -> None:
-    #     self.filter = SimpleITKFilter(N4BiasFieldCorrectionImageFilter())
-
     def __call__(self, image: Image) -> Image:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# def __post_init__(self) -> None:
# self.filter = SimpleITKFilter(N4BiasFieldCorrectionImageFilter())
def __call__(self, image: Image) -> Image:
🤖 Prompt for AI Agents
In src/imgtools/transforms/intensity_transforms.py around lines 174 to 176,
remove the commented-out __post_init__ block (the two lines that instantiate
SimpleITKFilter with N4BiasFieldCorrectionImageFilter) because it is dead code;
if the intent was to keep it as a reminder, either open a tracking issue or add
a TODO with a link to that issue, otherwise simply delete the commented lines to
clean up the codebase.

def __call__(self, image: Image) -> Image:
"""Apply N4 bias-field correction to an image.

Parameters
----------
image : Image
The input MR image to apply bias-field correction.
Returns
-------
Image
The MR image after applying N4 bias field correction.
"""
return bias_correction(image)
13 changes: 12 additions & 1 deletion src/imgtools/transforms/transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
IntensityTransform,
SpatialTransform,
)
from imgtools.transforms.intensity_transforms import N4BiasFieldCorrection

# Define TypeVars for the different image types
T_MedImage = TypeVar("T_MedImage", bound=MedImage)
Expand Down Expand Up @@ -71,7 +72,17 @@ def _apply_transforms(
elif isinstance(
transform, (IntensityTransform, SpatialTransform)
):
transformed_image = transform(transformed_image)
# Apply N4BiasFieldCorrection only for MR images
if isinstance(transform, N4BiasFieldCorrection):
if (
transformed_image.metadata.get(
"Modality", "Unknown"
)
== "MR"
):
transformed_image = transform(transformed_image)
else:
transformed_image = transform(transformed_image)
else:
msg = f"Invalid transform type: {type(transform)}"
raise ValueError(msg)
Expand Down
Loading