How to use the pydicom.dataset.FileDataset function in pydicom

To help you get started, we’ve selected a few pydicom examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github pydicom / pydicom / tests / test_filereader.py View on Github external
b'\x01\x01\x02\x03')  # VR of OL
        ds.PotentialReasonsForProcedure = ['A', 'B',
                                           'C']  # VR of UC, odd length
        ds.StrainDescription = 'Test'  # Even length
        ds.URNCodeValue = 'http://test.com'  # VR of UR
        ds.RetrieveURL = 'ftp://test.com  '  # Test trailing spaces ignored
        ds.DestinationAE = '    TEST  12    '  # 16 characters max for AE

        self.fp = BytesIO()  # Implicit little
        file_ds = FileDataset(self.fp, ds)
        file_ds.is_implicit_VR = True
        file_ds.is_little_endian = True
        file_ds.save_as(self.fp)

        self.fp_ex = BytesIO()  # Explicit little
        file_ds = FileDataset(self.fp_ex, ds)
        file_ds.is_implicit_VR = False
        file_ds.is_little_endian = True
        file_ds.save_as(self.fp_ex)
github pydicom / pydicom / tests / test_filewriter.py View on Github external
def test_write_explicit_vr_big_endian(self):
        """Test writing explicit big data for ambiguous elements."""
        # Create a dataset containing element with ambiguous VRs
        ref_ds = Dataset()
        ref_ds.PixelRepresentation = 1
        ref_ds.SmallestValidPixelValue = b'\x00\x01' # Big endian 1

        fp = BytesIO()
        file_ds = FileDataset(fp, ref_ds)
        file_ds.is_implicit_VR = False
        file_ds.is_little_endian = False
        file_ds.save_as(fp)
        fp.seek(0)

        ds = read_dataset(fp, False, False)
        self.assertEqual(ds.SmallestValidPixelValue, 1)
        self.assertEqual(ds[0x00280104].VR, 'SS')
github pymedphys / pymedphys / packages / pymedphys_pinnacle / src / pymedphys_pinnacle / exporttool / rtdose.py View on Github external
# Get the UID for the Dose and the Plan
    doseInstanceUID = plan.dose_inst_uid
    planInstanceUID = plan.plan_inst_uid

    # Populate required values for file meta information
    file_meta = Dataset()
    file_meta.MediaStorageSOPClassUID = RTDoseSOPClassUID
    file_meta.TransferSyntaxUID = GTransferSyntaxUID
    file_meta.MediaStorageSOPInstanceUID = doseInstanceUID
    file_meta.ImplementationClassUID = GImplementationClassUID

    # Create the FileDataset instance (initially no data elements, but
    # file_meta supplied)
    RDfilename = "RD." + file_meta.MediaStorageSOPInstanceUID + ".dcm"
    ds = FileDataset(RDfilename, {}, file_meta=file_meta, preamble=b'\x00' * 128)
    ds.SpecificCharacterSet = 'ISO_IR 100'
    ds.InstanceCreationDate = time.strftime("%Y%m%d")
    ds.InstanceCreationTime = time.strftime("%H%M%S")

    ds.SOPClassUID = RTDoseSOPClassUID  # RT Dose Storage
    ds.SOPInstanceUID = doseInstanceUID
    datetimesplit = plan_info["ObjectVersion"]["WriteTimeStamp"].split()
    # Read more accurate date from trial file if it is available
    trial_info = plan.trial_info
    if trial_info:
      datetimesplit = trial_info['ObjectVersion']['WriteTimeStamp'].split()

    ds.StudyDate = datetimesplit[0].replace('-', '')
    ds.StudyTime = datetimesplit[1].replace(':', '')
    ds.AccessionNumber = ''
    ds.Modality = RTDOSEModality
github pambros / CNN-2D-X-Ray-Catheter-Detection / python / common / UtilImage.py View on Github external
def SaveDicomSequence(_filename, _sequence):
	file_meta = Dataset()
	# file_meta.MediaStorageSOPClassUID = '1.2.840.10008.5.1.4.1.1.2'  # CT Image Storage
	file_meta.MediaStorageSOPClassUID = '1.2.3.4.5.1.4.1.1.2'  # need valid UID here for real work
	file_meta.MediaStorageSOPInstanceUID = "1.2.3"  # need valid UID here for real work
	file_meta.ImplementationClassUID = "1.2.3.4"  # need valid UIDs here

	# Create the FileDataset instance (initially no data elements, but file_meta supplied)
	ds = FileDataset(_filename, {}, file_meta=file_meta, preamble=b"\0" * 128)

	# Add the data elements -- not trying to set all required here. Check DICOM standard
	# ds.PatientName = "Test^Firstname"
	# ds.PatientID = "123456"

	# Set the transfer syntax
	ds.is_little_endian = True
	ds.is_implicit_VR = True # implicit VR (0002,0010) TransferSyntaxUID: 1.2.840.10008.1.2
	# ds.is_implicit_VR = False # explicit VR (0002,0010) TransferSyntaxUID: 1.2.840.10008.1.2.1

	# 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
github radiasoft / sirepo / sirepo / template / rs4pi.py View on Github external
def _create_dicom_dataset(study_uid, dicom_class, modality):
    sop_uid = dicom.uid.generate_uid()

    file_meta = dicom.dataset.Dataset()
    file_meta.MediaStorageSOPClassUID = _DICOM_CLASS[dicom_class]
    file_meta.MediaStorageSOPInstanceUID = sop_uid
    #TODO(pjm): need proper implementation uid
    file_meta.ImplementationClassUID = "1.2.3.4"
    file_meta.ImplementationVersionName = 'dcm4che-2.0'

    ds = dicom.dataset.FileDataset('', {}, file_meta=file_meta, preamble=b"\0" * 128)
    now = datetime.datetime.now()
    ds.InstanceCreationDate = now.strftime('%Y%m%d')
    ds.InstanceCreationTime = now.strftime('%H%M%S.%f')
    ds.SOPClassUID = _DICOM_CLASS[dicom_class]
    ds.SOPInstanceUID = sop_uid
    ds.StudyDate = ''
    ds.StudyTime = ''
    ds.AccessionNumber = ''
    ds.Modality = modality
    ds.Manufacturer = _RADIASOFT_ID
    ds.ReferringPhysiciansName = ''
    ds.ManufacturersModelName = _RADIASOFT_ID
    ds.PatientsName = _RADIASOFT_ID
    ds.PatientID = _RADIASOFT_ID
    ds.PatientsBirthDate = ''
    ds.PatientsSex = ''
github pydicom / pydicom / pydicom / dicomdir.py View on Github external
"""
        # Usually this class is created through filereader.read_partial,
        # and it checks class SOP, but in case of direct creation,
        # check here also
        if file_meta:
            class_uid = file_meta.MediaStorageSOPClassUID
            if not class_uid.name == "Media Storage Directory Storage":
                msg = "SOP Class is not Media Storage Directory (DICOMDIR)"
                raise InvalidDicomError(msg)
        if is_implicit_VR or not is_little_endian:
            msg = ('Invalid transfer syntax for DICOMDIR - '
                   'Implicit Little Endian expected.')
            if config.enforce_valid_values:
                raise InvalidDicomError(msg)
            warnings.warn(msg, UserWarning)
        FileDataset.__init__(
            self,
            filename_or_obj,
            dataset,
            preamble,
            file_meta,
            is_implicit_VR=is_implicit_VR,
            is_little_endian=is_little_endian)
        self.parse_records()
github pydicom / pydicom / examples / input_output / plot_write_dicom.py View on Github external
# Create some temporary filenames
suffix = '.dcm'
filename_little_endian = tempfile.NamedTemporaryFile(suffix=suffix).name
filename_big_endian = tempfile.NamedTemporaryFile(suffix=suffix).name

print("Setting file meta information...")
# Populate required values for 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...")
# Create the FileDataset instance (initially no data elements, but file_meta
# supplied)
ds = FileDataset(filename_little_endian, {},
                 file_meta=file_meta, preamble=b"\0" * 128)

# Add the data elements -- not trying to set all required here. Check DICOM
# standard
ds.PatientName = "Test^Firstname"
ds.PatientID = "123456"

# 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
github ericspod / Eidolon / eidolon / plugins / DicomPlugin.py View on Github external
# calculate intercept and slope
            intercept=image.imgmin
            imgrange=image.imgmax-intercept
            slope=max(1,imgrange/float(maxrange)) # slope is 1 if values are all within the range of dtype, otherwise is a scaling value

            # convert pixel array to the correct data type and scaling by slope/intercept
            pixel_array=((np.asarray(image.img)-intercept)/slope).astype(dtype)

            # create and fill in a dataset object the file requires
            file_meta = Dataset()
            metatags=list(defaultfiletags.items())+list(fileMetaTags.items())
            for k,v in metatags:
                setattr(file_meta,k,v)

            # create and fill in the file-specific dataset
            ds = FileDataset(filename, {},file_meta = file_meta,preamble="\0"*128)
            filetags=list(defaultdatasettags.items())+list(datasetTags.items())
            for k,v in filetags:
                setattr(ds,k,v)

            # set specific values for this image
            ds.RescaleSlope=slope
            ds.RescaleIntercept=intercept
            ds.Columns = pixel_array.shape[1]
            ds.Rows = pixel_array.shape[0]
            ds.ImagePositionPatient=list(image.position)
            ds.ImageOrientationPatient=list(image.orientation*vec3(1,0,0))+list(image.orientation*vec3(0,-1,0))
            ds.TriggerTime=int(image.timestep)
            ds.PixelSpacing=list(image.spacing)
            ds.SliceLocation=0#s*ds.SliceThickness
            ds.SeriesDescription=obj.getName()
            ds.PixelData = pixel_array.tostring()