Metadata-Version: 2.4
Name: dicom_parser
Version: 1.3.0
Summary: Deprecated: DICOM files parser meant to facilitate data access. See the README for maintained replacements.
Home-page: https://github.com/open-dicom/dicom_parser
Author: Zvi Baratz
Author-email: z.baratz@gmail.com
License: MIT
Project-URL: Source, https://github.com/open-dicom/dicom_parser/
Project-URL: Documentation, https://dicom-parser.readthedocs.io/en/latest/
Keywords: dicom,dcm,mri,ct,radiology
Classifier: Development Status :: 7 - Inactive
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Healthcare Industry
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3 :: Only
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.21
Requires-Dist: pydicom<4,>=2.1
Provides-Extra: magic
Requires-Dist: python-magic~=0.4; platform_system != "Windows" and extra == "magic"
Provides-Extra: dist
Requires-Dist: build; extra == "dist"
Requires-Dist: twine; extra == "dist"
Provides-Extra: docs
Requires-Dist: sphinx>=7; extra == "docs"
Requires-Dist: sphinx-rtd-theme>=2; extra == "docs"
Provides-Extra: pandas
Requires-Dist: jinja2; extra == "pandas"
Requires-Dist: pandas; extra == "pandas"
Provides-Extra: test
Requires-Dist: coverage[toml]>=6.2; extra == "test"
Requires-Dist: pytest>=7; extra == "test"
Requires-Dist: python-magic~=0.4; platform_system != "Windows" and extra == "test"
Provides-Extra: dev
Requires-Dist: black~=22.1; extra == "dev"
Requires-Dist: doc8~=0.10; extra == "dev"
Requires-Dist: flake8~=4.0; extra == "dev"
Requires-Dist: ipython; extra == "dev"
Requires-Dist: isort~=5.10; extra == "dev"
Requires-Dist: pre-commit; extra == "dev"
Requires-Dist: pre-commit-hooks; extra == "dev"
Requires-Dist: sphinx>=7; extra == "dev"
Requires-Dist: sphinx-rtd-theme>=2; extra == "dev"
Requires-Dist: coverage[toml]>=6.2; extra == "dev"
Requires-Dist: pytest>=7; extra == "dev"
Requires-Dist: python-magic~=0.4; platform_system != "Windows" and extra == "dev"
Provides-Extra: all
Requires-Dist: black~=22.1; extra == "all"
Requires-Dist: doc8~=0.10; extra == "all"
Requires-Dist: flake8~=4.0; extra == "all"
Requires-Dist: ipython; extra == "all"
Requires-Dist: isort~=5.10; extra == "all"
Requires-Dist: pre-commit; extra == "all"
Requires-Dist: pre-commit-hooks; extra == "all"
Requires-Dist: sphinx>=7; extra == "all"
Requires-Dist: sphinx-rtd-theme>=2; extra == "all"
Requires-Dist: coverage[toml]>=6.2; extra == "all"
Requires-Dist: pytest>=7; extra == "all"
Requires-Dist: python-magic~=0.4; platform_system != "Windows" and extra == "all"
Requires-Dist: build; extra == "all"
Requires-Dist: twine; extra == "all"
Requires-Dist: jinja2; extra == "all"
Requires-Dist: pandas; extra == "all"
Dynamic: license-file

# dicom_parser

> **dicom_parser is deprecated and no longer maintained.** Version 1.3.0 is the last release. It works with
> pydicom 2.1 to 3.x on Python 3.9 to 3.14, and it will get no further fixes. Everything it did is now covered
> by maintained tools. The guide below maps each feature to its replacement.

*dicom_parser* wrapped [pydicom][] to return "pythonic" values from DICOM headers, and added Siemens-specific
parsing: CSA headers, mosaics and diffusion vectors. Since it was written, pydicom 3, [nibabel][], [csa_header][]
and [dcm2niix][] have come to cover all of it, with active maintainers and wider testing.

* [Replacing dicom_parser](#replacing-dicom_parser)
* [Known problems in dicom_parser's results](#known-problems-in-dicom_parsers-results)
* [Installing the last release](#installing-the-last-release)
* [Credits](#credits)

---

## Replacing dicom_parser

| dicom_parser | Use instead |
|---|---|
| `Image`, `Header`: reading a file, dict-like access by keyword or tag | `pydicom.dcmread` and pydicom's `Dataset` |
| Parsed values (DS, IS, DA, TM, DT, PN) | pydicom: numbers are already `float`/`int` subclasses; dates and times with one config switch |
| `Header.keyword_contains`, `to_dict`, `to_dataframe` | `Dataset.dir`, `Dataset.to_json_dict`, a short pandas snippet |
| Siemens private tags by keyword (`B_value`, `MosaicRefAcqTimes`, …) | pydicom's `Dataset.private_block` |
| `CsaHeader`, `parse_ascconv` | [csa_header][] (`CsaHeader`), or `nibabel.nicom.ascconv.parse_ascconv` |
| `Image.data` (rescaling, Siemens mosaics, enhanced multi-frame) | `pydicom.pixels.apply_rescale`; nibabel's DICOM wrappers |
| `affine`, `slice_normal`, `spatial_resolution`, `image_position` | nibabel's DICOM wrappers |
| `b_matrix`, `q_vector`, `b_vector`, `b_value` | nibabel's DICOM wrappers |
| `Series` | a few lines of pydicom, or [dcm2niix][] for whole volumes |
| `detected_sequence`, `bids_path` | dcm2niix's `BidsGuess`; [HeuDiConv][], [dcm2bids][] or [BIDScoin][] for whole studies |
| Verbose code strings (`"MR"` → `"Magnetic Resonance"`) | none: pydicom returns the codes |

Each replacement below was checked against dicom_parser's own test files.

### Reading files and header values

```python
import pydicom

pydicom.config.datetime_conversion = True  # DA, TM and DT values become date/time objects

ds = pydicom.dcmread("image.dcm")
ds.ImagingFrequency          # DS: already a float subclass
ds.InstanceNumber            # IS: already an int subclass
ds.StudyDate                 # a datetime.date subclass
ds.PatientName.family_name   # PN components
ds.get("MissingKeyword", "default")
ds[0x0018, 0x0050].value     # access by tag
ds.dir("echo")               # keywords containing "echo"
ds.to_json_dict()            # the whole header as a dict
```

Age strings such as `"027Y"` stay strings in pydicom. To get years:

```python
AGE_UNITS_PER_YEAR = {"Y": 1, "M": 12, "W": 52.1429, "D": 365.2422}
age_in_years = float(ds.PatientAge[:-1]) / AGE_UNITS_PER_YEAR[ds.PatientAge[-1]]
```

For a table of the header, like `Header.to_dataframe`:

```python
import pandas as pd

header_table = pd.DataFrame(
    [(str(element.tag), element.keyword, element.VR, element.VM, element.value) for element in ds],
    columns=["Tag", "Keyword", "VR", "VM", "Value"],
).set_index("Tag")
```

### Siemens private tags

pydicom knows the Siemens private dictionary, so private elements come back typed:

```python
block = ds.private_block(0x0019, "SIEMENS MR HEADER")
block[0x0A].value   # NumberOfImagesInMosaic
block[0x0C].value   # B_value
block[0x0E].value   # DiffusionGradientDirection
block[0x28].value   # BandwidthPerPixelPhaseEncode
block[0x29].value   # MosaicRefAcqTimes (slice timing, ms)
```

The B matrix (`block[0x27]`) is stored as its 6 upper-triangle values. To get the 3×3 matrix:

```python
import numpy as np

upper_triangle = np.asarray(block[0x27].value, dtype=float)
b_matrix = upper_triangle[[0, 1, 2, 1, 3, 4, 2, 4, 5]].reshape(3, 3)
```

### Siemens CSA headers

dicom_parser's CSA parser now lives on as [csa_header][], and gives the same result. The only change is that each
tag's `index` field is gone (csa_header 2.0 dropped it):

```python
from csa_header import CsaHeader  # pip install "csa_header>=2.0.1"

image_csa = CsaHeader(ds[0x0029, 0x1010].value).read()
series_csa = CsaHeader(ds[0x0029, 0x1020].value).read()
image_csa["B_value"]["value"]
protocol = series_csa["MrPhoenixProtocol"]["value"]  # the parsed ASCCONV protocol
protocol["sDiffusion"]["lDiffDirections"]
```

To parse ASCCONV text yourself, `parse_ascconv` has the same signature and output in csa_header
(`csa_header.ascii.ascconv`) and in nibabel (`nibabel.nicom.ascconv`).

### Pixel data, mosaics and multi-frame images

```python
from pydicom.pixels import apply_rescale

pixels = apply_rescale(ds.pixel_array, ds)  # applies RescaleSlope and RescaleIntercept
```

For Siemens mosaics and enhanced multi-frame images, nibabel unpacks and scales the data, and returns geometry that
matches it:

```python
from nibabel.nicom import dicomwrappers

wrapper = dicomwrappers.wrapper_from_file("image.dcm")
volume = wrapper.get_data()   # a mosaic unpacked to 3D; a multi-frame image sorted into N-D
wrapper.affine                # voxel indices to patient coordinates (DICOM LPS, mm)
wrapper.voxel_sizes
wrapper.slice_normal
wrapper.image_position
```

nibabel orders the axes differently from dicom_parser, so the arrays are transposed and flipped relative to
`Image.data`. The voxels are the same, and nibabel's affine matches nibabel's axes.

### Diffusion

For Siemens DWI, nibabel's wrapper gives the same voxel-space values dicom_parser computed:

```python
dwi = dicomwrappers.wrapper_from_file("dwi.dcm")
dwi.b_matrix   # voxel space, as Image.voxel_space_b_matrix
dwi.q_vector
dwi.b_vector
dwi.b_value    # as Image.voxel_space_b_value
```

### Series

```python
from pathlib import Path

import numpy as np
import pydicom
from pydicom.misc import is_dicom
from pydicom.pixels import apply_rescale

paths = [path for path in Path("series_directory").rglob("*") if path.is_file() and is_dicom(path)]
datasets = sorted((pydicom.dcmread(path) for path in paths), key=lambda dataset: dataset.InstanceNumber)
volume = np.stack([apply_rescale(dataset.pixel_array, dataset) for dataset in datasets], axis=-1)
echo_times = {dataset.EchoTime for dataset in datasets}
```

`is_dicom` finds DICOM files by content, as `Series(path, mime=True)` did, without libmagic. To turn a series into a
NIfTI volume with correct geometry, use [dcm2niix][].

### Sequence detection and BIDS names

dcm2niix writes a JSON sidecar next to each volume (`dcm2niix -b y …`). Its `BidsGuess` field gives the BIDS data
type and entities, e.g. `["func", "_acq-epfid2p2m2_dir-AP_run-11_bold"]`, or `["discard", …]` for a localizer. To
organise a whole study into BIDS, use [HeuDiConv][], [dcm2bids][] or [BIDScoin][]. All three let you write the
rules that dicom_parser hard-coded.

### Verbose code strings

dicom_parser expanded some code strings (`Modality`, `PatientPosition`, `PatientSex`, `ScanningSequence`,
`SequenceVariant`), e.g. `"HFS"` to `"Head First-Supine"`. pydicom returns the codes themselves. If you need the long
forms, the tables are in [`src/dicom_parser/utils/code_strings/`](src/dicom_parser/utils/code_strings/) (MIT
licensed).

---

## Known problems in dicom_parser's results

Comparing dicom_parser with the replacements on its own test files found these errors. If your results depend on
any of them, re-check them with the tools above.

* **`Image.affine` on Siemens mosaics** disagrees with dcm2niix's conversion by up to 283 mm for the same voxel. Its
  slice normal points the opposite way, and the affine does not follow the axis flips that `Image.data` applies to
  the mosaic. nibabel's affine for the same file agrees with dcm2niix.
* **`spatial_resolution`, and therefore `affine`,** take the slice size from `SliceThickness` rather than from the
  spacing between slices, so they are wrong when slices have gaps
  ([#84](https://github.com/open-dicom/dicom_parser/issues/84)).
* **`Header.n_diffusion_directions`** always returns `None`.
* **`Header.phase_encoding_direction`** disagrees with dcm2niix for row (left–right) phase encoding: `i-` where
  dcm2niix gives `i`.

---

## Installing the last release

```bash
pip install dicom_parser
```

Version 1.3.0 supports pydicom 2.1 to 3.x and Python 3.9 to 3.14. It warns on import that the package is
deprecated. The [documentation site][] still describes the full API.

---

## Credits

Written by Zvi Baratz during his PhD at Tel Aviv University, with contributions from
[@GalKepler](https://github.com/GalKepler), [@matthew-brett](https://github.com/matthew-brett),
[@taleinat](https://github.com/taleinat), [@Aharonyn](https://github.com/Aharonyn),
[@jstorrs](https://github.com/jstorrs), [@LilianYou](https://github.com/LilianYou) and
[@juliam98](https://github.com/juliam98). The CSA header parsing builds on nibabel's `nicom` module, and continues
in [csa_header][]. To cite dicom_parser, use its [Zenodo record](https://zenodo.org/badge/latestdoi/241392223).

[BIDScoin]: https://github.com/Donders-Institute/bidscoin
[csa_header]: https://github.com/open-dicom/csa_header
[dcm2bids]: https://github.com/UNFmontreal/Dcm2Bids
[dcm2niix]: https://github.com/rordenlab/dcm2niix
[HeuDiConv]: https://github.com/nipy/heudiconv
[nibabel]: https://github.com/nipy/nibabel
[pydicom]: https://github.com/pydicom/pydicom
[documentation site]: https://dicom-parser.readthedocs.io/
