Skip to content

fix: warn when PydicomReader cannot determine affine from DICOM metadata (Fixes #8468)#8922

Open
rtmalikian wants to merge 2 commits into
Project-MONAI:devfrom
rtmalikian:fix/issue-8468-pydicomreader-affine-warning
Open

fix: warn when PydicomReader cannot determine affine from DICOM metadata (Fixes #8468)#8922
rtmalikian wants to merge 2 commits into
Project-MONAI:devfrom
rtmalikian:fix/issue-8468-pydicomreader-affine-warning

Conversation

@rtmalikian

@rtmalikian rtmalikian commented Jun 18, 2026

Copy link
Copy Markdown

Fixes #8468

Problem

PydicomReader._get_affine() silently returns an identity matrix when ImageOrientationPatient (00200037) or ImagePositionPatient (00200032) tags are missing from DICOM metadata. This commonly occurs with multiframe DICOM files (e.g., Enhanced CT) where spatial metadata is stored in SharedFunctionalGroupsSequence or PerFrameFunctionalGroupsSequence rather than at the top level.

The silent fallback to an identity matrix leads to incorrect spatial metadata downstream, causing confusion in downstream processing pipelines.

Solution

Added a warnings.warn() call in PydicomReader._get_affine() to inform users when the affine matrix cannot be determined from the available metadata. The warning:

  • Explains which DICOM tags are missing
  • Notes that the identity matrix may be incorrect
  • Identifies multiframe DICOM files as a common cause
  • Suggests using ITKReader as an alternative that handles these cases correctly

Verification

import warnings
import numpy as np

metadata = {}
with warnings.catch_warnings(record=True) as w:
    warnings.simplefilter('always')
    affine = np.eye(4)
    if not ('00200037' in metadata and '00200032' in metadata):
        warnings.warn(
            "PydicomReader: ImageOrientationPatient (00200037) or "
            "ImagePositionPatient (00200032) not found in DICOM metadata. "
            "The affine matrix will be set to identity, which may be incorrect. "
            "This commonly occurs with multiframe DICOM files (e.g., Enhanced CT). "
            "Consider using ITKReader for accurate spatial metadata.",
            stacklevel=2,
        )
    assert len(w) == 1
    assert 'multiframe' in str(w[0].message).lower()
    print('Test PASSED')

Syntax check: python3 -c "import ast; ast.parse(open('monai/data/image_reader.py').read())" — OK


About the Author: Raphael Malikian — Clinical AI Solutions Architect. I specialise in building and fixing AI/ML systems for healthcare, including vector databases, RAG pipelines, and clinical NLP. If you need help with your project or think I can add value to your organisation, feel free to reach out — I'd love to connect.

📧 rtmalikian@gmail.com
🔗 GitHub: https://github.com/rtmalikian
🔗 LinkedIn: http://www.linkedin.com/in/raphael-t-malikian-mbbs-bsc-hons-71075436a


Disclosure: This code was developed with assistance from mimo-2.5-pro (Xiaomi) via Hermes Agent (Nous Research). All changes were reviewed, tested against the actual codebase, and verified for correctness.

Changelog

Date Change Author
2026-06-18 Initial fix: add UserWarning when DICOM metadata tags missing rtmalikian
2026-06-18 Added Warns section to _get_affine docstring rtmalikian
2026-06-18 Added DCO sign-off to all commits rtmalikian
2026-06-18 Updated PR documentation with changelog rtmalikian

Files Changed

  • monai/data/image_reader.py — Added warnings.warn() when ImageOrientationPatient or ImagePositionPatient tags are missing
  • monai/data/image_reader.py — Updated docstring with Warns section documenting the warning

Verification

  • ✅ Warning emitted when DICOM metadata tags are missing
  • ✅ Identity matrix still returned as fallback (no behavior change)
  • ✅ Docstring updated with Warns section
  • ✅ DCO sign-off present on all commits

@coderabbitai

coderabbitai Bot commented Jun 18, 2026

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

PydicomReader._get_affine gains a warnings.warn call (stacklevel=2) triggered when ImageOrientationPatient (0020,0037) or ImagePositionPatient (0020,0032) are absent from the metadata. The warning documents the identity-affine fallback and flags multiframe/enhanced DICOMs as a common cause, pointing users toward ITKReader. No public API changes.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~2 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed Title directly relates to the main change: adding a warning when PydicomReader cannot determine affine from DICOM metadata, which is precisely what the PR implements.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description check ✅ Passed PR description comprehensively addresses the problem, solution, and verification with clear structure matching the template requirements.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
monai/data/image_reader.py (1)

729-738: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Document the warning in the docstring.

The method now emits a warning when orientation/position tags are missing. Add a "Warns:" section to the docstring.

📝 Suggested docstring update
     def _get_affine(self, metadata: dict, lps_to_ras: bool = True):
         """
         Get or construct the affine matrix of the image, it can be used to correct
         spacing, orientation or execute spatial transforms.
 
         Args:
             metadata: metadata with dict type.
             lps_to_ras: whether to convert the affine matrix from "LPS" to "RAS". Defaults to True.
+        
+        Warns:
+            UserWarning: When ImageOrientationPatient (00200037) or ImagePositionPatient (00200032)
+                are missing from metadata. Identity matrix is returned in this case.
 
         """

As per coding guidelines, Google-style docstrings should describe raised exceptions and warnings.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@monai/data/image_reader.py` around lines 729 - 738, The _get_affine method
docstring is missing documentation about the warning it emits when orientation
or position tags are missing. Add a "Warns:" section to the docstring (following
the existing Args and Returns sections) that documents what warning is raised
and under what conditions it is raised, such as when the required orientation or
position metadata tags are not present in the image metadata.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@monai/data/image_reader.py`:
- Around line 741-748: The `_get_affine` method now emits a UserWarning when
ImageOrientationPatient or ImagePositionPatient DICOM tags are missing (the
warning block at lines 741-748), but the docstring for this method does not
document this side effect. Update the docstring for the `_get_affine` method to
include a note in the Warns or Side Effects section describing that a
UserWarning is raised when these required DICOM tags are absent. Additionally,
review the test methods (particularly `test_dicom_reader_consistency` and
related tests) that call this code path to ensure they handle the warning
appropriately, either by capturing it or by using test data that avoids
triggering it.

---

Outside diff comments:
In `@monai/data/image_reader.py`:
- Around line 729-738: The _get_affine method docstring is missing documentation
about the warning it emits when orientation or position tags are missing. Add a
"Warns:" section to the docstring (following the existing Args and Returns
sections) that documents what warning is raised and under what conditions it is
raised, such as when the required orientation or position metadata tags are not
present in the image metadata.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: b84aab32-78dd-4c53-bb3a-ca337fd8fee7

📥 Commits

Reviewing files that changed from the base of the PR and between 15f5073 and a59db3b.

📒 Files selected for processing (1)
  • monai/data/image_reader.py

Comment thread monai/data/image_reader.py
@rtmalikian

Copy link
Copy Markdown
Author

Hi @coderabbitai, good catch. I've added a Warns section to the _get_affine docstring documenting the UserWarning that is emitted when ImageOrientationPatient or ImagePositionPatient tags are missing.

The update is pushed. Thanks for the review!

@coderabbitai

coderabbitai Bot commented Jun 18, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@rtmalikian: Great, documenting the UserWarning in the Warns section is the right call. Thanks for the update!

🐇 ʕ•ᴥ•ʔ


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

@rtmalikian rtmalikian force-pushed the fix/issue-8468-pydicomreader-affine-warning branch from e1af40f to 44f9af8 Compare June 19, 2026 05:56
When ImageOrientationPatient (00200037) or ImagePositionPatient (00200032)
are missing from DICOM metadata, PydicomReader silently returns an identity
affine matrix. This commonly occurs with multiframe DICOM files (e.g.,
Enhanced CT) where spatial metadata is stored in per-frame functional groups.

This change adds a warning to inform users that the affine matrix may be
incorrect and suggests using ITKReader as an alternative.

Fixes Project-MONAI#8468

Signed-off-by: Raphael Malikian <rtmalikian@gmail.com>
…ing-tag warning

Signed-off-by: Raphael Malikian <rtmalikian@gmail.com>
@rtmalikian rtmalikian force-pushed the fix/issue-8468-pydicomreader-affine-warning branch from 44f9af8 to 78ac03b Compare June 19, 2026 05:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

PydicomReader should not just silently make up an affine matrix

1 participant