diff --git a/mu_map/file/dicom.py b/mu_map/file/dicom.py index d8426f779240cb004969e2fdd3e74fc26c4b933c..b216e18164c41d550b6eb8c1528c001d4a3b12bb 100644 --- a/mu_map/file/dicom.py +++ b/mu_map/file/dicom.py @@ -1,3 +1,4 @@ +from datetime import datetime, timedelta from typing import Tuple import numpy as np @@ -15,6 +16,12 @@ DCM_TAG_PIXEL_SCALE_FACTOR = 0x00331038 Maximum value that can be stored in an unsigned integer with 16 bist. """ UINT16_MAX = 2**16 - 1 +""" +DICOM images always contain UIDs to indicate their uniqueness. +Thus, when a DICOM image is updated, UIDs have to be changed for +which the following prefix is used. +""" +UID_PREFIX = "1.2.826.0.1.3680043.2.521." def load_dcm(filename: str) -> Tuple[pydicom.dataset.FileDataset, np.ndarray]: @@ -89,3 +96,21 @@ def update_dcm( dcm.LargestImagePixelValue = image.max() dcm[DCM_TAG_PIXEL_SCALE_FACTOR].value = scale return dcm + +def change_uid(dcm: pydicom.dataset.FileDataset) -> pydicom.dataset.FileDataset: + """ + Change the UIDs (SeriesInstance and SOPInstance) in a DICOM header so that + it becomes its own unique file. Note that this method does not guarantee + that the UIDs are fully unique. Since the creation of UIDs is time dependent, + this function should not be used to rapidly change many UIDs. + + :param dcm: the DICOM file to be udpated + :return: the DICOM file with updated UIDs + """ + + now = datetime.now() + soon = now + timedelta(seconds=1) + + dcm.SeriesInstanceUID = UID_PREFIX + now.strftime("%Y%m%d%H%M%S") + dcm.SOPInstanceUID = UID_PREFIX + soon.strftime("%Y%m%d%H%M%S") + return dcm diff --git a/mu_map/file/interfile2dicom.py b/mu_map/file/interfile2dicom.py index cb4d71e296509929cbb748d5088661e5deb116e1..b4ce0b1512a051fc4cec241f8a2083d94c501176 100644 --- a/mu_map/file/interfile2dicom.py +++ b/mu_map/file/interfile2dicom.py @@ -4,8 +4,8 @@ import os import numpy as np import pydicom -from mu_map.file.dicom import update_dcm -from mu_map.file.interfile import read_interfile +from mu_map.file.dicom import update_dcm, change_uid +from mu_map.file.interfile import load_interfile_img parser = argparse.ArgumentParser( description="convert an INTERFILE image to a DICOM image", @@ -25,13 +25,21 @@ parser.add_argument( type=str, help="the output file - defaults to the INTERFILE input with a dcm extension", ) +parser.add_argument( + "--description", + type=str, + help="if provided the series description will be updated", +) args = parser.parse_args() if args.out is None: args.out = os.path.splitext(args.inter)[0] + ".dcm" -image, header = read_interfile(args.inter) +image = load_interfile_img(args.inter) dcm = pydicom.dcmread(args.dcm) dcm = update_dcm(dcm.copy(), image) +dcm = change_uid(dcm) +if args.description: + dcm.SeriesDescription = args.description pydicom.dcmwrite(args.out, dcm)