Example #1
0
def _write_dicom_file(np_slice: np.ndarray, header: pydicom.FileDataset,
                      file_path: str):
    """Replace data in header with 2D numpy array and write to `file_path`.

    Args:
        np_slice (np.ndarray): 2D slice to encode in dicom file.
        header (pydicom.FileDataset): DICOM header.
        file_path: File path to write to.
    """
    # Deep copy required in case headers are shared.
    header = copy.deepcopy(header)
    expected_dimensions = header.Rows, header.Columns
    assert (
        np_slice.shape == expected_dimensions
    ), "In-plane dimension mismatch - expected shape {}, got {}".format(
        str(expected_dimensions), str(np_slice.shape))

    np_slice_bytes = np_slice.tobytes()
    bit_depth = int(
        len(np_slice_bytes) / (np_slice.shape[0] * np_slice.shape[1]) * 8)
    if bit_depth != header.BitsAllocated:
        np_slice = _update_np_dtype(np_slice, header.BitsAllocated)
        np_slice_bytes = np_slice.tobytes()
        bit_depth = int(
            len(np_slice_bytes) / (np_slice.shape[0] * np_slice.shape[1]) * 8)

    assert bit_depth == header.BitsAllocated, "Bit depth mismatch: Expected {:d} got {:d}".format(
        header.BitsAllocated, bit_depth)

    header.PixelData = np_slice_bytes

    header.save_as(file_path)
Example #2
0
    def __write_dicom_file__(self, np_slice: np.ndarray,
                             header: pydicom.FileDataset, filepath: str):
        """
        Replace data in header with 2D numpy array and write to filepath
        :param np_slice: a 2D numpy array
        :param header: a pydicom.FileDataset with fields populated
        :param filepath: Filepath to write dicom to
        """
        expected_dimensions = header.Rows, header.Columns
        assert np_slice.shape == expected_dimensions, "In-plane dimension mismatch - expected shape %s, got %s" % (
            str(expected_dimensions), str(np_slice.shape))

        np_slice_bytes = np_slice.tobytes()
        bit_depth = int(
            len(np_slice_bytes) / (np_slice.shape[0] * np_slice.shape[1]) * 8)
        if bit_depth != header.BitsAllocated:
            np_slice = __update_np_dtype__(np_slice, header.BitsAllocated)
            np_slice_bytes = np_slice.tobytes()
            bit_depth = int(
                len(np_slice_bytes) / (np_slice.shape[0] * np_slice.shape[1]) *
                8)

        assert bit_depth == header.BitsAllocated, "Bit depth mismatch: Expected %d got %d" % (
            header.BitsAllocated, bit_depth)

        header.PixelData = np_slice_bytes

        header.save_as(filepath)
Example #3
0
    def create_dcm_file(self):
        suffix = '.dcm'
        filename_little_endian = tempfile.NamedTemporaryFile(
            suffix=suffix).name
        filename_big_endian = tempfile.NamedTemporaryFile(suffix=suffix).name

        print("Setting file meta information...")
        file_meta = Dataset()
        file_meta.MediaStorageSOPClassUID = '1.2.840.10008.5.1.4.1.1.2'
        file_meta.MediaStorageSOPInstanceUID = "1.2.3"
        file_meta.ImplementationClassUID = "1.2.3.4"

        print("Setting dataset values...")

        ds = FileDataset(filename_little_endian, {},
                         file_meta=file_meta,
                         preamble=b"\0" * 128)

        ds.PatientName = self.get_patient_name(
        ) + " " + self.get_patient_surname()
        ds.PatientID = self.get_patient_id()
        ds.PatientSex = self.get_patient_sex()
        ds.PatientAge = self.get_patient_age()
        ds.PatientWeight = self.get_patient_weight()
        ds.ImageComment = self.get_patient_comment()
        ds.PatientBirthDate = self.get_patient_birth()

        # Set the transfer syntax
        ds.is_little_endian = True
        ds.is_implicit_VR = True

        # Set creation date/time
        dt = datetime.datetime.now()
        ds.ContentDate = dt.strftime('%Y%m%d')
        timeStr = dt.strftime('%H%M%S.%f')  # long format with micro seconds
        ds.ContentTime = timeStr
        ds.BitsAllocated = 16
        ds.Rows = self.image.shape[0]
        ds.Columns = self.image.shape[1]
        ds.PixelRepresentation = 0
        ds.SamplesPerPixel = 1
        ds.PhotometricInterpretation = "MONOCHROME2"
        image = self.image
        image *= 255
        image = image.astype("uint16")
        ds.PixelData = Image.fromarray(image).tobytes()
        print("Writing test file", filename_little_endian)
        ds.save_as(filename_little_endian)
        print("File saved.")

        ds.file_meta.TransferSyntaxUID = pydicom.uid.ExplicitVRBigEndian
        ds.is_little_endian = False
        ds.is_implicit_VR = False

        print("Writing test file as Big Endian Explicit VR",
              filename_big_endian)
        ds.save_as(filename_big_endian)
        return ds
Example #4
0
def generate_dicom_scans(dst, num_scans=10, intercept=0, slope=1):
    spacing = (0.4 + 0.4 * np.random.rand(num_scans, 3) +
               np.array([1 + 0.5 * np.random.rand(), 0, 0]))
    origin = np.random.randint(-200, 200, (num_scans, 3))
    for i in range(num_scans):
        num_slices = np.random.randint(128, 169)
        scan_id = np.random.randint(2**16)
        scan_data = np.random.randint(0, 256, (num_slices, 128, 128))
        folder = os.path.join(dst,
                              hex(scan_id).replace('x', '').upper().zfill(8))

        if not os.path.exists(folder):
            os.makedirs(folder)

        for k in range(num_slices):
            slice_name = (hex(scan_id + k).replace('x', '').upper().zfill(8))
            filename = os.path.join(folder, slice_name)
            pixel_array = (scan_data[k, ...] - intercept) / slope
            locZ = float(origin[i, 0] + spacing[i, 0] * k)
            locY, locX = float(origin[i, 1]), float(origin[i, 2])

            file_meta = DicomDataset()
            file_meta.MediaStorageSOPClassUID = "Secondary Capture Image Storage"
            file_meta.MediaStorateSOPInstanceUID = (hex(scan_id).replace(
                'x', '').upper().zfill(8))

            file_meta.ImplementationClassUID = slice_name

            dataset = DicomFileDataset(filename, {},
                                       file_meta=file_meta,
                                       preamble=b"\0" * 128)

            dataset.PixelData = pixel_array.astype(np.uint16).tostring()
            dataset.RescaleSlope = slope
            dataset.RescaleIntercept = intercept

            dataset.ImagePositionPatient = MultiValue(
                type_constructor=float, iterable=[locZ, locY, locX])

            dataset.PixelSpacing = MultiValue(
                type_constructor=float,
                iterable=[float(spacing[i, 1]),
                          float(spacing[i, 2])])
            dataset.SliceThickness = float(spacing[i, 0])

            dataset.Modality = 'WSD'
            dataset.Columns = pixel_array.shape[0]
            dataset.Rows = pixel_array.shape[1]
            dataset.file_meta.TransferSyntaxUID = pydicom.uid.ImplicitVRLittleEndian
            dataset.PixelRepresentation = 1
            dataset.BitsAllocated = 16
            dataset.BitsStored = 16
            dataset.SamplesPerPixel = 1

            write_file(filename, dataset)
Example #5
0
def dump_dicom(data, folder, spacing=(1, 1, 1),
               origin=(0, 0, 0), intercept=0, slope=1):
    """ Dump 3D scan in dicom format.

    Parameters
    ----------
    data : ndarray
        3D numpy array containing ct scan's data.
    folder : str
        folder where dicom files will be dumped.
    spacing : ArrayLike
        ndarray of shape (3,) that contains spacing along z, y, x axes.
    origin : ArrayLike
        ndarray of shape (3,) that contains origin for z, y, x axes.
    interception : float
        interception value. Default is 0.
    slope : float
        slope value. Default is 1.
    """
    spacing = np.array(spacing).reshape(-1)
    origin = np.array(origin).reshape(-1)

    if not os.path.exists(folder):
        os.makedirs(folder)

    num_slices = data.shape[0]
    scan_id = np.random.randint(2 ** 16)
    for i in range(num_slices):
        slice_name = (
            hex(scan_id + i)
            .replace('x', '')
            .upper()
            .zfill(8)
        )
        filename = os.path.join(folder, slice_name)
        pixel_array = (data[i, ...] - intercept) / slope
        locZ, locY, locX = (float(origin[0] + spacing[0] * i),
                            float(origin[1]), float(origin[2]))

        file_meta = Dataset()
        file_meta.MediaStorageSOPClassUID = 'Secondary Capture Image Storage'
        file_meta.MediaStorageSOPInstanceUID = (
            hex(scan_id)
            .replace('x', '')
            .upper()
            .zfill(8)
        )
        file_meta.ImplementationClassUID = slice_name

        dataset = FileDataset(filename, {},
                              file_meta=file_meta,
                              preamble=b"\0"*128)

        dataset.PixelData = pixel_array.astype(np.uint16).tostring()
        dataset.RescaleSlope = slope
        dataset.RescaleIntercept = intercept

        dataset.ImagePositionPatient = MultiValue(type_constructor=float,
                                                  iterable=[locZ, locY, locX])

        dataset.PixelSpacing = MultiValue(type_constructor=float,
                                          iterable=[float(spacing[1]),
                                                    float(spacing[2])])
        dataset.SliceThickness = float(spacing[0])

        dataset.Modality = 'WSD'
        dataset.Columns = pixel_array.shape[0]
        dataset.Rows = pixel_array.shape[1]
        dataset.file_meta.TransferSyntaxUID = pydicom.uid.ImplicitVRLittleEndian
        dataset.PixelRepresentation = 1
        dataset.BitsAllocated = 16
        dataset.BitsStored = 16
        dataset.SamplesPerPixel = 1

        write_file(filename, dataset)
Example #6
0
    def generate_common_dicom_dataset_series(self, slice_count: int,
                                             system: Modality) -> list:
        output_dataset = []
        slice_pos = 0
        slice_thickness = 0
        study_uid = generate_uid()
        series_uid = generate_uid()
        frame_of_ref_uid = generate_uid()
        date_ = datetime.now().date()
        age = timedelta(days=45 * 365)
        time_ = datetime.now().time()
        cols = 2
        rows = 2
        bytes_per_voxel = 2

        for i in range(0, slice_count):
            file_meta = Dataset()
            pixel_array = b"\0" * cols * rows * bytes_per_voxel
            file_meta.MediaStorageSOPClassUID = sop_classes[system][1]
            file_meta.MediaStorageSOPInstanceUID = generate_uid()
            file_meta.ImplementationClassUID = generate_uid()

            tmp_dataset = FileDataset('', {},
                                      file_meta=file_meta,
                                      preamble=pixel_array)
            tmp_dataset.file_meta.TransferSyntaxUID = "1.2.840.10008.1.2.1"
            tmp_dataset.SliceLocation = slice_pos + i * slice_thickness
            tmp_dataset.SliceThickness = slice_thickness
            tmp_dataset.WindowCenter = 1
            tmp_dataset.WindowWidth = 2
            tmp_dataset.AcquisitionNumber = 1
            tmp_dataset.InstanceNumber = i
            tmp_dataset.SeriesNumber = 1
            tmp_dataset.ImageOrientationPatient = [
                1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000
            ]
            tmp_dataset.ImagePositionPatient = [
                0.0, 0.0, tmp_dataset.SliceLocation
            ]
            tmp_dataset.ImageType = ['ORIGINAL', 'PRIMARY', 'AXIAL']
            tmp_dataset.PixelSpacing = [1, 1]
            tmp_dataset.PatientName = 'John Doe'
            tmp_dataset.FrameOfReferenceUID = frame_of_ref_uid
            tmp_dataset.SOPClassUID = sop_classes[system][1]
            tmp_dataset.SOPInstanceUID = generate_uid()
            tmp_dataset.SeriesInstanceUID = series_uid
            tmp_dataset.StudyInstanceUID = study_uid
            tmp_dataset.BitsAllocated = bytes_per_voxel * 8
            tmp_dataset.BitsStored = bytes_per_voxel * 8
            tmp_dataset.HighBit = (bytes_per_voxel * 8 - 1)
            tmp_dataset.PixelRepresentation = 1
            tmp_dataset.Columns = cols
            tmp_dataset.Rows = rows
            tmp_dataset.SamplesPerPixel = 1
            tmp_dataset.AccessionNumber = '2'
            tmp_dataset.AcquisitionDate = date_
            tmp_dataset.AcquisitionTime = datetime.now().time()
            tmp_dataset.AdditionalPatientHistory = 'UTERINE CA PRE-OP EVAL'
            tmp_dataset.ContentDate = date_
            tmp_dataset.ContentTime = datetime.now().time()
            tmp_dataset.Manufacturer = 'Mnufacturer'
            tmp_dataset.ManufacturerModelName = 'Model'
            tmp_dataset.Modality = sop_classes[system][0]
            tmp_dataset.PatientAge = '064Y'
            tmp_dataset.PatientBirthDate = date_ - age
            tmp_dataset.PatientID = 'ID0001'
            tmp_dataset.PatientIdentityRemoved = 'YES'
            tmp_dataset.PatientPosition = 'FFS'
            tmp_dataset.PatientSex = 'F'
            tmp_dataset.PhotometricInterpretation = 'MONOCHROME2'
            tmp_dataset.PixelData = pixel_array
            tmp_dataset.PositionReferenceIndicator = 'XY'
            tmp_dataset.ProtocolName = 'some protocole'
            tmp_dataset.ReferringPhysicianName = ''
            tmp_dataset.SeriesDate = date_
            tmp_dataset.SeriesDescription = 'test series '
            tmp_dataset.SeriesTime = time_
            tmp_dataset.SoftwareVersions = '01'
            tmp_dataset.SpecificCharacterSet = 'ISO_IR 100'
            tmp_dataset.StudyDate = date_
            tmp_dataset.StudyDescription = 'test study'
            tmp_dataset.StudyID = ''
            if (system == Modality.CT):
                tmp_dataset.RescaleIntercept = 0
                tmp_dataset.RescaleSlope = 1
            tmp_dataset.StudyTime = time_
            output_dataset.append(tmp_dataset)
        return output_dataset