Skip to content

Commit

Permalink
cleaned up reading of dicom metadata
Browse files Browse the repository at this point in the history
  • Loading branch information
tclose committed Sep 18, 2024
1 parent c1c15bc commit 13711b8
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 15 deletions.
45 changes: 30 additions & 15 deletions extras/fileformats/extras/application/medical.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import typing as ty
from pathlib import Path
import pydicom
import pydicom.tag
from fileformats.core import FileSet, extra_implementation
from fileformats.application import Dicom
import medimages4tests.dummy.dicom.mri.t1w.siemens.skyra.syngo_d13c
Expand All @@ -10,22 +10,11 @@
@extra_implementation(FileSet.read_metadata)
def dicom_read_metadata(
dicom: Dicom,
specific_tags: ty.Optional[ty.Collection[str]] = None,
specific_tags: ty.Optional[pydicom.tag.TagListType] = None,
**kwargs: ty.Any,
) -> ty.Mapping[str, ty.Any]:
dcm = pydicom.dcmread(
dicom.fspath,
specific_tags=list(specific_tags if specific_tags is not None else []),
)
[getattr(dcm, a, None) for a in dir(dcm)] # Ensure all keywords are set
metadata = {
e.keyword: e.value
for e in dcm.elements()
if isinstance(e, pydicom.DataElement)
and getattr(e, "keyword", False)
and e.keyword != "PixelData"
}
return metadata
dcm = pydicom.dcmread(dicom.fspath, specific_tags=specific_tags)
return pydicom_to_dict(dcm)


@extra_implementation(FileSet.generate_sample_data)
Expand All @@ -38,3 +27,29 @@ def dicom_generate_sample_data(
out_dir=generator.dest_dir
).iterdir()
)


def pydicom_to_dict(
dcm: pydicom.Dataset, omit: ty.Collection[str] = ("PixelData",)
) -> ty.Dict[str, ty.Any]:
"""Convert a pydicom Dataset to a dictionary.
Parameters
----------
dcm : pydicom.Dataset
The pydicom Dataset to convert.
omit : Collection[str], optional
A collection of keys to omit from the dictionary, by default ("PixelData",)
"""
# Ensure that all keys are loaded before creating dictionary otherwise the keywords
# will not be set in the elem
[getattr(dcm, attr, None) for attr in dir(dcm)]
dct: ty.Dict[str, ty.Any] = {}
for elem in dcm.values():
if isinstance(elem, pydicom.DataElement) and elem.keyword:
key = elem.keyword
else:
key = elem.tag.json_key
if key not in omit:
dct[key] = elem.value
return dct
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import pytest
from fileformats.application import Dicom


Expand All @@ -6,3 +7,12 @@ def test_dicom_metadata():
dicom = Dicom.sample()

assert dicom.metadata["EchoTime"] == "2.07"


def test_dicom_metadata_with_specific_tags():

dicom = Dicom(Dicom.sample(), specific_tags=["EchoTime"])

assert dicom.metadata["EchoTime"] == "2.07"
with pytest.raises(KeyError):
dicom.metadata["PatientName"]

0 comments on commit 13711b8

Please sign in to comment.