Mercurial > repos > imgteam > highdicom_dicom2text
changeset 0:5da9fe99cf02 draft default tip
planemo upload for repository https://github.com/BMCV/galaxy-image-analysis/tree/master/tools/highdicom/ commit 3a064f9bbb0eb56d752df40eb467b74da31711ce
| author | imgteam |
|---|---|
| date | Thu, 01 Jan 2026 10:27:32 +0000 |
| parents | |
| children | |
| files | creators.xml dicom2text.py dicom2text.xml dicom2tiff.py macros.xml test-data/SC_rgb_rle_2frame.tiff test-data/ct_image.tiff test-data/ct_image_float16.tiff test-data/dx_image.tiff test-data/heart_ct_5813.dcm test-data/highdicom/LICENSE test-data/highdicom/ct_image.dcm test-data/highdicom/dx_image.dcm test-data/highdicom/seg_image_ct_binary.dcm test-data/highdicom/sm_image.dcm test-data/pydicom/LICENSE test-data/pydicom/SC_rgb_rle_2frame.dcm test-data/seg_image_ct_binary.tiff test-data/seg_image_ct_binary_unnormalized.tiff test-data/sm_image.tiff tests.xml |
| diffstat | 21 files changed, 528 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/creators.xml Thu Jan 01 10:27:32 2026 +0000 @@ -0,0 +1,43 @@ +<macros> + + <xml name="creators/bmcv"> + <organization name="Biomedical Computer Vision Group, Heidelberg Universtiy" alternateName="BMCV" url="http://www.bioquant.uni-heidelberg.de/research/groups/biomedical_computer_vision.html" /> + <yield /> + </xml> + + <xml name="creators/kostrykin"> + <person givenName="Leonid" familyName="Kostrykin"/> + <yield/> + </xml> + + <xml name="creators/rmassei"> + <person givenName="Riccardo" familyName="Massei"/> + <yield/> + </xml> + + <xml name="creators/alliecreason"> + <person givenName="Allison" familyName="Creason"/> + <yield/> + </xml> + + <xml name="creators/bugraoezdemir"> + <person givenName="Bugra" familyName="Oezdemir"/> + <yield/> + </xml> + + <xml name="creators/thawn"> + <person givenName="Till" familyName="Korten"/> + <yield/> + </xml> + + <xml name="creators/pavanvidem"> + <person givenName="Pavan" familyName="Videm"/> + <yield/> + </xml> + + <xml name="creators/tuncK"> + <person givenName="Tunc" familyName="Kayikcioglu"/> + <yield/> + </xml> + +</macros>
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/dicom2text.py Thu Jan 01 10:27:32 2026 +0000 @@ -0,0 +1,40 @@ +import argparse +import json +import pathlib + +import pydicom +import yaml + + +def dicom_to_text( + dcm_filepath: pathlib.Path, + text_filepath: pathlib.Path, +): + dcm = pydicom.dcmread(dcm_filepath, stop_before_pixels=True) + data = dcm.to_json_dict() + fmt_suffix = text_filepath.suffix.lower() + + # Export JSON + if fmt_suffix == '.json': + with text_filepath.open('w') as json_fp: + json.dump(data, json_fp, indent=2) + + # Export YAML + elif fmt_suffix in ('.yml', '.yaml'): + with text_filepath.open('w') as fp: + yaml.dump(data, fp) + + else: + raise ValueError(f'Unknown suffix: "{fmt_suffix}"') + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('dcm', type=pathlib.Path) + parser.add_argument('text', type=pathlib.Path) + args = parser.parse_args() + + dicom_to_text( + args.dcm, + args.text, + )
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/dicom2text.xml Thu Jan 01 10:27:32 2026 +0000 @@ -0,0 +1,72 @@ +<tool id="highdicom_dicom2text" name="Export DICOM metadata" version="@TOOL_VERSION@+galaxy@VERSION_SUFFIX@" profile="24.01"> + <expand macro="description"/> + <macros> + <import>macros.xml</import> + <import>creators.xml</import> + </macros> + <creator> + <expand macro="creators/bmcv"/> + <expand macro="creators/kostrykin"/> + </creator> + <edam_operations> + <edam_operation>operation_3443</edam_operation> + </edam_operations> + <expand macro="xrefs"/> + <expand macro="requirements"/> + <command><![CDATA[ + + python '$__tool_directory__/dicom2text.py' + '$input' + + #if $export_to == "json" + ./output.json + #elif $export_to == "yaml" + ./output.yaml + #end if + + ]]> + </command> + <inputs> + <param name="input" type="data" format="binary" label="DICOM dataset"/> + <param name="export_to" type="select" label="Export to"> + <option value="json" selected="true">JSON</option> + <option value="yaml">YAML</option> + </param> + </inputs> + <outputs> + <data format="json" name="output_json" from_work_dir="output.json" label="${tool.name} on ${on_string} (JSON)"> + <filter>export_to == 'json'</filter> + </data> + <data format="yaml" name="output_yaml" from_work_dir="output.yaml" label="${tool.name} on ${on_string} (YAML)"> + <filter>export_to == 'yaml'</filter> + </data> + </outputs> + <tests> + <test expect_num_outputs="1"> + <param name="input" value="highdicom/ct_image.dcm"/> + <param name="export_to" value="json"/> + <output name="output_json" ftype="json"> + <assert_contents> + <has_json_property_with_value property="00080080" value='{"vr": "LO", "Value": ["JFK IMAGING CENTER"]}'/> + </assert_contents> + </output> + </test> + <test expect_num_outputs="1"> + <param name="input" value="highdicom/sm_image.dcm"/> + <param name="export_to" value="yaml"/> + <output name="output_yaml" ftype="yaml"> + <assert_contents> + <has_text_matching expression="00080104:\n +Value:\n +- Brightfield illumination\n"/> + </assert_contents> + </output> + </test> + </tests> + <help> + + **Exports the metadata of a DICOM dataset as JSON or YAML.** + + @DICOM_INTRO@ + + </help> + <expand macro="citations"/> +</tool>
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/dicom2tiff.py Thu Jan 01 10:27:32 2026 +0000 @@ -0,0 +1,180 @@ +import argparse +import pathlib +import sys +from typing import ( + get_args, + Literal, +) + +import giatools +import highdicom +import numpy as np +import pydicom + + +FrameAxis = Literal['T', 'Z', 'Q'] +frame_axes = get_args(FrameAxis) + + +def dicom_to_tiff( + dcm_filepath: pathlib.Path, + tiff_filepath: pathlib.Path, + multiframe_axis: FrameAxis, + normalize_label_maps: bool, + config: dict, +): + assert multiframe_axis in frame_axes, ( + f'Not a valid axis for DICOM frames: "{multiframe_axis}"' + ) + dcm = highdicom.imread(dcm_filepath) + metadata = dict(unit='mm') # DICOM always uses millimeters as the unit of measurement + + # If the image is a tiled image, ... + if dcm.is_tiled: + print('DICOM dataset is a tiled multi-frame image') + + # ...extract the top-level WSI by combining the frames (tiles) into a mosaic + arr = dcm.get_total_pixel_matrix(**config) + axes = 'YX' if arr.ndim == 2 else 'YXC' + + # Read metadata for the WSI size, infer the resolution + if ( + (width := getattr(dcm, 'ImagedVolumeWidth', 0)) > 0 and + (height := getattr(dcm, 'ImagedVolumeHeight', 0)) > 0 + ): + metadata.setdefault('resolution', (arr.shape[1] / width, arr.shape[0] / height)) + + # Check if the image is a 3-D volume. According to the docs [1], `highdicom.Image.get_volume_geometry` + # will succeed (i.e. return a non-None) if the data *is* a 3-D volume, or if it is a tiled mosaic. + # Hence, to distinguish tiled images from 3-D volumes, we use the `elif` branching semantic. + # + # [1] https://highdicom.readthedocs.io/en/latest/package.html#highdicom.Image.get_volume_geometry + # + # So, if the image is a 3-D volume, ... + elif (volume_geom := dcm.get_volume_geometry()) is not None: + + # ...extract the 3-D volume by joining the frames (z-slices) + arr = dcm.get_volume(**config).array + axes = 'ZYX' if arr.ndim == 3 else 'ZYXC' + + # Print status info + if arr.shape[0] == 1: + print('DICOM dataset is a slice of a 3-D volume') + else: + print('DICOM dataset is a 3-D volume') + + # Read metadata for spacing between pixels and slices, infer the resolution + metadata.setdefault('resolution', tuple(np.divide(1, volume_geom.pixel_spacing))) + metadata.setdefault('z_spacing', volume_geom.spacing_between_slices) + + # Infer metadata for z-position + if ( + (ipp := getattr(dcm, 'ImagePositionPatient', None)) and + (iop := getattr(dcm, 'ImageOrientationPatient', None)) + ): + normal = np.cross(iop[:3], iop[3:]) + metadata.setdefault('z_position', float(normal @ ipp)) + + # Otherwise, extract a raw stack of frames + else: + print( + 'DICOM dataset is an unknown multi-frame image' + if dcm.number_of_frames > 1 else + 'DICOM dataset is a single-frame image' + ) + arr = dcm.get_frames(**config) + + # Construct OME-TIFF axes string + axes = 'YX' + if dcm.number_of_frames >= 1: + axes = f'{multiframe_axis}{axes}' + if len(axes) < arr.ndim: + axes += 'C' + + # Normalize singleton axes + if axes[0] in frame_axes and arr.shape[0] == 1: + arr = arr[0] + axes = axes[1:] + + # Normalize label maps + if dcm.SOPClassUID == pydicom.uid.SegmentationStorage: + print('DICOM dataset is a label map') + if normalize_label_maps: + arr = normalize_label_map(arr) + + # Read pixel spacing metadata (if available) and infer the resolution (if it wasn't determined yet) + if (pixel_spacing := getattr(dcm, 'PixelSpacing', None)): + metadata.setdefault('resolution', tuple(np.divide(1, pixel_spacing))) + + # Write TIFF file + print('Output TIFF shape:', arr.shape) + print('Output TIFF axes:', axes) + print('Output TIFF', metadata_to_str(metadata)) + giatools.Image(arr, axes, metadata=metadata).write(str(tiff_filepath)) + + +def normalize_label_map(arr: np.ndarray) -> np.ndarray: + labels = np.unique(arr) + num_labels = len(labels) + + # Choose appropriate data type + if num_labels < 2: + print(f'Too few labels ({num_labels}), skipping normalization') + norm_dtype = None + elif num_labels <= 0xff: + norm_dtype = np.uint8 + norm_max_label = 0xff + elif num_labels <= 0xffff: + norm_dtype = np.uint16 + norm_max_label = 0xffff + else: + print(f'Too many labels ({num_labels}), skipping normalization') + norm_dtype = None + + # Create normalized label map + if norm_dtype is not None: + norm_arr = np.zeros(arr.shape, norm_dtype) + for label_idx, label in enumerate(sorted(labels)): + norm_label = (norm_max_label * label_idx) // (len(labels) - 1) + cc = (arr == label) + norm_arr[cc] = norm_label + + # Verify that the normalization was loss-less, and return + # (normalization should never fail, but better check) + if len(np.unique(norm_arr)) != num_labels: + print('Label map normalization failed', file=sys.stderr) + return arr # this should never happen in practice, but better check + else: + return norm_arr + + +def metadata_to_str(metadata: dict) -> str: + tokens = list() + for key in sorted(metadata.keys()): + value = metadata[key] + if isinstance(value, tuple): + value = '(' + ', '.join([f'{val}' for val in value]) + ')' + tokens.append(f'{key}: {value}') + return ', '.join(tokens) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('dcm', type=pathlib.Path) + parser.add_argument('tiff', type=pathlib.Path) + parser.add_argument('multiframe_axis', type=str, choices=frame_axes, help='OME-TIFF axis to be used for the frames of a multi-frame DICOM file') + parser.add_argument('dtype', type=str) + parser.add_argument('--normalize_label_maps', default=False, action='store_true') + parser.add_argument('--apply_voi_transform', default=False, action='store_true') + args = parser.parse_args() + + dicom_to_tiff( + args.dcm, + args.tiff, + multiframe_axis=args.multiframe_axis, + normalize_label_maps=args.normalize_label_maps, + config=dict( + dtype=args.dtype or None, # use `None` instead of an empty string + apply_voi_transform=args.apply_voi_transform, + ), + )
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/macros.xml Thu Jan 01 10:27:32 2026 +0000 @@ -0,0 +1,32 @@ +<macros> + <token name="@TOOL_VERSION@">0.27.0</token> + <token name="@VERSION_SUFFIX@">0</token> + <xml name="description"> + <description>with highdicom</description> + </xml> + <xml name="xrefs"> + <xrefs> + <xref type="bio.tools">galaxy_image_analysis</xref> + <xref type="bio.tools">highdicom</xref> + </xrefs> + </xml> + <xml name="requirements"> + <requirements> + <requirement type="package" version="@TOOL_VERSION@">highdicom</requirement> + <requirement type="package" version="3.0.1">pydicom</requirement> + <requirement type="package" version="0.5.2">giatools</requirement> + <requirement type="package" version="6.0.3">pyyaml</requirement> + </requirements> + </xml> + <token name="@DICOM_INTRO@"> + DICOM is a widely established file format in medical imaging. A DICOM dataset contains rich metadata (patient, study + info) and the actual medical image pixel or voxel data. The image data can be single-channel or multi-channel, and it + can also be organized in multiple frames (e.g., spatial tiles of a mosaic, spatial slices, or time steps). + </token> + <xml name="citations"> + <citations> + <citation type="doi">10.1007/s10278-022-00683-y</citation> + <citation type="doi">10.5281/zenodo.13824606</citation> + </citations> + </xml> +</macros>
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test-data/highdicom/LICENSE Thu Jan 01 10:27:32 2026 +0000 @@ -0,0 +1,7 @@ +Copyright 2020 MGH Computational Pathology + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test-data/pydicom/LICENSE Thu Jan 01 10:27:32 2026 +0000 @@ -0,0 +1,59 @@ +License file for pydicom, a pure-python DICOM library + +Copyright (c) 2008-2020 Darcy Mason and pydicom contributors + +Except for portions outlined below, pydicom is released under an MIT license: + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +Portions of pydicom (private dictionary file(s)) were generated from the +private dictionary of the GDCM library, released under the following license: + + Program: GDCM (Grassroots DICOM). A DICOM library + +Copyright (c) 2006-2016 Mathieu Malaterre +Copyright (c) 1993-2005 CREATIS +(CREATIS = Centre de Recherche et d'Applications en Traitement de l'Image) +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither name of Mathieu Malaterre, or CREATIS, nor the names of any + contributors (CNRS, INSERM, UCB, Universite Lyon I), may be used to + endorse or promote products derived from this software without specific + prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tests.xml Thu Jan 01 10:27:32 2026 +0000 @@ -0,0 +1,95 @@ +<macros> + + <!-- Macros for verification of image outputs --> + + <xml + name="tests/binary_image_diff" + tokens="name,value,ftype,metric,eps" + token_metric="mae" + token_eps="0.01"> + + <output name="@NAME@" value="@VALUE@" ftype="@FTYPE@" compare="image_diff" metric="@METRIC@" eps="@EPS@" pin_labels="0"> + <assert_contents> + <has_image_n_labels n="2"/> + <yield/> + </assert_contents> + </output> + + </xml> + + <xml + name="tests/label_image_diff" + tokens="name,value,ftype,metric,eps,pin_labels" + token_metric="iou" + token_eps="0.01" + token_pin_labels="0"> + + <output name="@NAME@" value="@VALUE@" ftype="@FTYPE@" compare="image_diff" metric="@METRIC@" eps="@EPS@" pin_labels="@PIN_LABELS@"> + <assert_contents> + <yield/> + </assert_contents> + </output> + + </xml> + + <xml + name="tests/intensity_image_diff" + tokens="name,value,ftype,metric,eps" + token_metric="rms" + token_eps="0.01"> + + <output name="@NAME@" value="@VALUE@" ftype="@FTYPE@" compare="image_diff" metric="@METRIC@" eps="@EPS@"> + <assert_contents> + <yield/> + </assert_contents> + </output> + + </xml> + + <!-- Variants of the above for verification of collection elements --> + + <xml + name="tests/binary_image_diff/element" + tokens="name,value,ftype,metric,eps" + token_metric="mae" + token_eps="0.01"> + + <element name="@NAME@" value="@VALUE@" ftype="@FTYPE@" compare="image_diff" metric="@METRIC@" eps="@EPS@" pin_labels="0"> + <assert_contents> + <has_image_n_labels n="2"/> + <yield/> + </assert_contents> + </element> + + </xml> + + <xml + name="tests/label_image_diff/element" + tokens="name,value,ftype,metric,eps" + token_metric="iou" + token_eps="0.01" + token_pin_labels="0"> + + <element name="@NAME@" value="@VALUE@" ftype="@FTYPE@" compare="image_diff" metric="@METRIC@" eps="@EPS@" pin_labels="@PIN_LABELS@"> + <assert_contents> + <yield/> + </assert_contents> + </element> + + </xml> + + <xml + name="tests/intensity_image_diff/element" + tokens="name,value,ftype,metric,eps" + token_metric="rms" + token_eps="0.01"> + + <element name="@NAME@" value="@VALUE@" ftype="@FTYPE@" compare="image_diff" metric="@METRIC@" eps="@EPS@"> + <assert_contents> + <yield/> + </assert_contents> + </element> + + </xml> + +</macros>
