-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Add clinical preprocessing utilities for CT and MRI modalities. #8659
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Hitendrasinhdata7
wants to merge
37
commits into
Project-MONAI:dev
from
Hitendrasinhdata7:clinical-dicom-preprocessing
+323
−0
Closed
Changes from 6 commits
Commits
Show all changes
37 commits
Select commit
Hold shift + click to select a range
5394658
Final commit: add clinical DICOM preprocessing files, workflow PDF, a…
Hitendrasinhdata7 aeabbbd
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 24665aa
Add clinical DICOM preprocessing Python module, test module, PDF; rem…
Hitendrasinhdata7 798f8af
Remove old notebook files after converting to .py modules
Hitendrasinhdata7 b3a6ac2
Add clinical DICOM preprocessing utilities for CT/MRI with unit tests
Hitendrasinhdata7 a446448
Update clinical preprocessing utilities and tests per CodeRabbit revi…
Hitendrasinhdata7 d7f134c
Refactor clinical preprocessing: add custom exceptions, use isinstanc…
Hitendrasinhdata7 ce7850f
Update clinical preprocessing: add Google-style Returns, parameter ch…
Hitendrasinhdata7 01b88fa
Fix clinical preprocessing module based on code review feedback
Hitendrasinhdata7 81b7f5b
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 821fc9a
Complete fix for all critical code review issues
Hitendrasinhdata7 1a15437
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] d12bd51
Hitendrasinh Rathod <[email protected]>
Hitendrasinhdata7 634136a
Merge branch 'clinical-dicom-preprocessing' of https://github.com/Hit…
Hitendrasinhdata7 34a7aa2
Complete fix for all CI and code review issues
Hitendrasinhdata7 3a493d4
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 2b0f6a7
Add MetaTensor import and return type hint
Hitendrasinhdata7 f0261b8
Hitendrasinh Rathod <[email protected]>
Hitendrasinhdata7 1418dcc
Merge branch 'clinical-dicom-preprocessing' of https://github.com/Hit…
Hitendrasinhdata7 1e68a5a
Fix docstring: add Returns section and correct Raises section formatting
Hitendrasinhdata7 7030e7d
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 441d48d
Add clinical preprocessing transforms
Hitendrasinhdata7 11dce12
Resolve merge conflict - keep clinical preprocessing module
Hitendrasinhdata7 f513c16
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 2986d2e
Fix CodeRabbit review issues
Hitendrasinhdata7 b3e8f87
Address CodeRabbit review suggestions
Hitendrasinhdata7 5a4fbb5
Final fixes per CodeRabbit review
Hitendrasinhdata7 c273cf7
Fix CI compliance: formatting, type hints, line length
Hitendrasinhdata7 d0961e1
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 9753c34
Fix CI compliance for clinical preprocessing
Hitendrasinhdata7 0daee66
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 885ae4b
Fix CodeRabbit issues: return type and exception classes
Hitendrasinhdata7 e50560d
Merge remote changes and fix CodeRabbit review issues
Hitendrasinhdata7 68038cb
Improve tests per CodeRabbit suggestions
Hitendrasinhdata7 b241ee6
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] c4c2303
Improve mock setup and add MRI validation
Hitendrasinhdata7 01b60f0
Merge formatting and apply test improvements
Hitendrasinhdata7 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Binary file not shown.
Binary file not shown.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,144 @@ | ||
| import numpy as np | ||
|
|
||
| from monai.transforms import ScaleIntensityRange, NormalizeIntensity | ||
| from monai.transforms.clinical_preprocessing import ( | ||
| get_ct_preprocessing_pipeline, | ||
| get_mri_preprocessing_pipeline, | ||
| preprocess_dicom_series, | ||
| ) | ||
| from unittest.mock import patch, MagicMock | ||
|
|
||
|
|
||
| def test_ct_windowing_range_and_shape(): | ||
| """Test CT windowing transform parameters.""" | ||
| rng = np.random.default_rng(0) | ||
|
|
||
| sample_ct = rng.integers( | ||
| -1024, 2048, size=(64, 64, 64), dtype=np.int16 | ||
| ) | ||
|
|
||
| transform = ScaleIntensityRange( | ||
| a_min=-1000, | ||
| a_max=400, | ||
| b_min=0.0, | ||
| b_max=1.0, | ||
| clip=True, | ||
| ) | ||
|
|
||
| output = transform(sample_ct) | ||
| output = np.asarray(output) | ||
|
|
||
| assert output.shape == sample_ct.shape | ||
| assert np.isfinite(output).all() | ||
| assert output.min() >= -1e-6 | ||
| assert output.max() <= 1.0 + 1e-6 | ||
|
|
||
|
|
||
| def test_mri_normalization_mean_std(): | ||
| """Test MRI normalization transform.""" | ||
| rng = np.random.default_rng(0) | ||
|
|
||
| sample_mri = rng.random((64, 64, 64), dtype=np.float32) | ||
|
|
||
| transform = NormalizeIntensity(nonzero=True) | ||
|
|
||
| output = transform(sample_mri) | ||
| output = np.asarray(output) | ||
|
|
||
| mean_val = float(output.mean()) | ||
| std_val = float(output.std()) | ||
|
|
||
| assert output.shape == sample_mri.shape | ||
| assert np.isclose(mean_val, 0.0, atol=0.1) | ||
| assert np.isclose(std_val, 1.0, atol=0.1) | ||
|
|
||
|
|
||
| def test_ct_preprocessing_pipeline(): | ||
| """Test CT preprocessing pipeline returns expected transform composition.""" | ||
| pipeline = get_ct_preprocessing_pipeline() | ||
|
|
||
| assert hasattr(pipeline, 'transforms') | ||
| assert len(pipeline.transforms) == 3 | ||
| assert pipeline.transforms[0].__class__.__name__ == 'LoadImage' | ||
| assert pipeline.transforms[1].__class__.__name__ == 'EnsureChannelFirst' | ||
| assert pipeline.transforms[2].__class__.__name__ == 'ScaleIntensityRange' | ||
|
|
||
|
|
||
| def test_mri_preprocessing_pipeline(): | ||
| """Test MRI preprocessing pipeline returns expected transform composition.""" | ||
| pipeline = get_mri_preprocessing_pipeline() | ||
|
|
||
| assert hasattr(pipeline, 'transforms') | ||
| assert len(pipeline.transforms) == 3 | ||
| assert pipeline.transforms[0].__class__.__name__ == 'LoadImage' | ||
| assert pipeline.transforms[1].__class__.__name__ == 'EnsureChannelFirst' | ||
| assert pipeline.transforms[2].__class__.__name__ == 'NormalizeIntensity' | ||
|
|
||
|
|
||
| @patch('monai.transforms.clinical_preprocessing.get_ct_preprocessing_pipeline') | ||
| def test_preprocess_dicom_series_ct(mock_pipeline): | ||
| """Test preprocess_dicom_series with CT modality.""" | ||
| mock_transform = MagicMock() | ||
| mock_pipeline.return_value = mock_transform | ||
|
|
||
| preprocess_dicom_series("dummy_path.dcm", "CT") | ||
|
|
||
| mock_pipeline.assert_called_once() | ||
| mock_transform.assert_called_once_with("dummy_path.dcm") | ||
|
|
||
|
|
||
| @patch('monai.transforms.clinical_preprocessing.get_ct_preprocessing_pipeline') | ||
| def test_preprocess_dicom_series_ct_lowercase(mock_pipeline): | ||
| """Test preprocess_dicom_series with CT modality in lowercase.""" | ||
| mock_transform = MagicMock() | ||
| mock_pipeline.return_value = mock_transform | ||
|
|
||
| preprocess_dicom_series("dummy_path.dcm", "ct") | ||
|
|
||
| mock_pipeline.assert_called_once() | ||
| mock_transform.assert_called_once_with("dummy_path.dcm") | ||
|
|
||
|
|
||
| @patch('monai.transforms.clinical_preprocessing.get_mri_preprocessing_pipeline') | ||
| def test_preprocess_dicom_series_mri(mock_pipeline): | ||
| """Test preprocess_dicom_series with MRI modality.""" | ||
| mock_transform = MagicMock() | ||
| mock_pipeline.return_value = mock_transform | ||
|
|
||
| preprocess_dicom_series("dummy_path.dcm", "MRI") | ||
|
|
||
| mock_pipeline.assert_called_once() | ||
| mock_transform.assert_called_once_with("dummy_path.dcm") | ||
|
|
||
|
|
||
| @patch('monai.transforms.clinical_preprocessing.get_mri_preprocessing_pipeline') | ||
| def test_preprocess_dicom_series_mr(mock_pipeline): | ||
| """Test preprocess_dicom_series with MR modality.""" | ||
| mock_transform = MagicMock() | ||
| mock_pipeline.return_value = mock_transform | ||
|
|
||
| preprocess_dicom_series("dummy_path.dcm", "MR") | ||
|
|
||
| mock_pipeline.assert_called_once() | ||
| mock_transform.assert_called_once_with("dummy_path.dcm") | ||
|
|
||
|
|
||
| def test_preprocess_dicom_series_invalid_modality(): | ||
| """Test preprocess_dicom_series raises ValueError for unsupported modality.""" | ||
| try: | ||
| preprocess_dicom_series("dummy_path.dcm", "PET") | ||
| assert False, "Should have raised ValueError" | ||
| except ValueError as e: | ||
| error_message = str(e) | ||
| assert "Unsupported modality" in error_message | ||
| assert "PET" in error_message | ||
| assert "CT, MR, MRI" in error_message | ||
|
|
||
|
|
||
| def test_preprocess_dicom_series_invalid_type(): | ||
| """Test preprocess_dicom_series raises TypeError for non-string modality.""" | ||
| try: | ||
| preprocess_dicom_series("dummy_path.dcm", 123) | ||
| assert False, "Should have raised TypeError" | ||
| except TypeError as e: | ||
| error_message = str(e) | ||
coderabbitai[bot] marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| """Clinical DICOM preprocessing utilities for CT and MRI modalities.""" | ||
|
|
||
| from typing import Union | ||
| from os import PathLike | ||
|
|
||
| from monai.data import MetaTensor | ||
| from monai.transforms import ( | ||
| Compose, | ||
| LoadImage, | ||
| EnsureChannelFirst, | ||
| ScaleIntensityRange, | ||
| NormalizeIntensity, | ||
| ) | ||
|
|
||
| # Use a tuple for programmatic checks and formatting | ||
| SUPPORTED_MODALITIES = ("CT", "MR", "MRI") | ||
|
|
||
|
|
||
| def get_ct_preprocessing_pipeline() -> Compose: | ||
| """ | ||
| Build a CT preprocessing pipeline using standard HU windowing. | ||
|
|
||
| The pipeline applies LoadImage, EnsureChannelFirst, and ScaleIntensityRange | ||
| with HU window [-1000, 400] normalized to [0.0, 1.0]. | ||
|
|
||
| Returns: | ||
| Compose: A composed transform pipeline for CT preprocessing. | ||
| """ | ||
| return Compose( | ||
| [ | ||
| LoadImage(image_only=True), | ||
| EnsureChannelFirst(), | ||
| ScaleIntensityRange( | ||
| a_min=-1000, | ||
| a_max=400, | ||
| b_min=0.0, | ||
| b_max=1.0, | ||
| clip=True, | ||
| ), | ||
| ] | ||
| ) | ||
|
|
||
|
|
||
| def get_mri_preprocessing_pipeline() -> Compose: | ||
| """ | ||
| Build an MRI preprocessing pipeline using intensity normalization. | ||
|
|
||
| The pipeline applies LoadImage, EnsureChannelFirst, and NormalizeIntensity | ||
| with nonzero=True to normalize only non-zero voxels. | ||
|
|
||
| Returns: | ||
| Compose: A composed transform pipeline for MRI preprocessing. | ||
| """ | ||
| return Compose( | ||
| [ | ||
| LoadImage(image_only=True), | ||
| EnsureChannelFirst(), | ||
| NormalizeIntensity(nonzero=True), | ||
| ] | ||
| ) | ||
|
|
||
|
|
||
| def preprocess_dicom_series( | ||
| dicom_path: Union[str, bytes, PathLike], | ||
| modality: str, | ||
| ) -> MetaTensor: | ||
| """ | ||
| Preprocess a DICOM series based on modality. | ||
|
|
||
| Args: | ||
| dicom_path: Path to DICOM file or directory. | ||
| modality: Imaging modality. Supported values: "CT", "MR", "MRI" (case-insensitive). | ||
|
|
||
| Returns: | ||
| MetaTensor: Preprocessed image with intensity values normalized based on modality. | ||
|
|
||
| Raises: | ||
| TypeError: If modality is not a string. | ||
| ValueError: If modality is not one of the supported values. | ||
| """ | ||
| if not isinstance(modality, str): | ||
| raise TypeError(f"modality must be a string, got {type(modality).__name__}") | ||
|
|
||
| modality = modality.strip().upper() | ||
|
|
||
| if modality == "CT": | ||
| transform = get_ct_preprocessing_pipeline() | ||
| elif modality in ("MR", "MRI"): | ||
| transform = get_mri_preprocessing_pipeline() | ||
| else: | ||
| raise ValueError( | ||
| f"Unsupported modality: {modality}. Supported values: {', '.join(SUPPORTED_MODALITIES)}" | ||
| ) | ||
|
|
||
| return transform(dicom_path) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.