本文整理匯總了Python中dicom.dataset.Dataset類的典型用法代碼示例。如果您正苦於以下問題:Python Dataset類的具體用法?Python Dataset怎麽用?Python Dataset使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了Dataset類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: WriteDCMFile
def WriteDCMFile(pixel_array,filename):
file_meta = Dataset()
file_meta.MediaStorageSOPClassUID = 'RT Image Storage'
file_meta.MediaStorageSOPInstanceUID = '1.3.6.1.4.1.9590.100.1.1.111165684411017669021768385720736873780'
file_meta.ImplementationClassUID = '1.3.6.1.4.1.9590.100.1.0.100.4.0'
ds = FileDataset(filename, {},file_meta = file_meta,preamble="\0"*128)
ds.Modality = 'RTIMAGE'
ds.ContentDate = str(datetime.date.today()).replace('-','')
ds.ContentTime = str(time.time()) #milliseconds since the epoch
ds.StudyInstanceUID = '1.3.6.1.4.1.9590.100.1.1.124313977412360175234271287472804872093'
ds.SeriesInstanceUID = '1.3.6.1.4.1.9590.100.1.1.369231118011061003403421859172643143649'
ds.SOPInstanceUID = '1.3.6.1.4.1.9590.100.1.1.111165684411017669021768385720736873780'
ds.SOPClassUID = 'RT Image Storage'
ds.SecondaryCaptureDeviceManufacturer = 'Varian Medical Systems'
## These are the necessary imaging components of the FileDataset object.
ds.SamplesPerPixel = 1
ds.ImagePlanePixelSpacing=[0.392,0.392]
ds.PhotometricInterpretation = "MONOCHROME2"
ds.PixelRepresentation = 0
ds.HighBit = 15
ds.BitsStored = 16
ds.BitsAllocated = 16
# ds.SmallestImagePixelValue = '\\x00\\x00'
# ds.LargestImagePixelValue = '\\xff\\xff'
ds.Columns =1024# pixel_array.shape[0]
ds.Rows =764# pixel_array.shape[1]
ds.RescaleSlope=1.0
ds.RescaleIntercept=1.0
# if type(pixel_array) != np.uint16:
# pixel_array =np.uint16(pixel_array)
ds.PixelData = pixel_array
ds.save_as(filename,write_like_original=True)
return
示例2: testUID
def testUID(self):
"""DataElement: setting or changing UID results in UID type........."""
ds = Dataset()
ds.TransferSyntaxUID = "1.2.3"
self.assert_(type(ds.TransferSyntaxUID) is UID, "Assignment to UID did not create UID class")
ds.TransferSyntaxUID += ".4.5.6"
self.assert_(type(ds.TransferSyntaxUID) is UID, "+= to UID did not keep as UID class")
示例3: write_dicom
def write_dicom(pixel_array, filename):
file_meta = Dataset()
file_meta.MediaStorageSOPClassUID = 'Secondary Capture Image Storage'
file_meta.MediaStorageSOPInstanceUID = '1.3.6.1.4.1.9590.100.1.1.111165684'
file_meta.MediaStorageSOPInstanceUID += '411017669021768385720736873780'
file_meta.ImplementationClassUID = '1.3.6.1.4.1.9590.100.1.0.100.4.0'
ds = FileDataset(filename, {}, file_meta=file_meta, preamble=b"\0"*128)
ds.Modality = 'MR'
ds.ContentDate = str(date.today()).replace('-', '')
ds.ContentTime = str(time())
ds.StudyInstanceUID = '1.3.6.1.4.1.9590.100.1.1.1243139774123601752342712'
ds.StudyInstanceUID += '87472804872093'
ds.SeriesInstanceUID = '1.3.6.1.4.1.9590.100.1.1.369231118011061003403421'
ds.SeriesInstanceUID += '859172643143649'
ds.SOPInstanceUID = '1.3.6.1.4.1.9590.100.1.1.111165684411017669021768385'
ds.SOPInstanceUID += '720736873780'
ds.SOPClassUID = 'Secondary Capture Image Storage'
ds.SecondaryCaptureDeviceManufctur = 'Python 3.3.5'
# Options
ds.InstitutionName = "Imperial College London"
ds.RepetitionTime = 300
# These are the necessary imaging components of the FileDataset object.
ds.SamplesPerPixel = 1
ds.PhotometricInterpretation = "MONOCHROME2"
ds.PixelRepresentation = 0
ds.HighBit = 15
ds.BitsStored = 16
ds.BitsAllocated = 16
ds.Columns = pixel_array.shape[1]
ds.Rows = pixel_array.shape[0]
ds.PixelData = pixel_array.tostring()
ds.save_as(filename)
return 0
示例4: create_dicom
def create_dicom(private_tag,payload,filename):
""" Function creates minimal dicom file from scratch with required tags
and stores payload (string) in the specified private tag.
"""
# create empty dicomfile
file_meta = Dataset()
# Raw Data Storage
file_meta.MediaStorageSOPClassUID = '1.2.840.10008.5.1.4.1.1.66'
# unieke uid's
file_meta.MediaStorageSOPInstanceUID = dicom.UID.generate_uid()
file_meta.ImplementationClassUID = dicom.UID.generate_uid()
ds = FileDataset(filename, {},file_meta = file_meta,preamble="\0"*128)
ds.SOPClassUID = '1.2.840.10008.5.1.4.1.1.7' # secondary capture SOP UID
ds.SOPInstanceUID = file_meta.MediaStorageSOPInstanceUID
ds.StudyInstanceUID = dicom.UID.generate_uid()
ds.SeriesInstanceUID = dicom.UID.generate_uid()
ds.PatientID = PatientID
ds.PatientName = PatientName
ds.StudyDescription = StudyDescription
ds.SeriesDescription = SeriesDescription
ds.Modality = 'OT'
ds.StudyDate = time.strftime('%Y%m%d')
ds.SeriesDate = ds.StudyDate
ds.ContentDate = ds.StudyDate
ds.StudyTime = ds.SeriesTime = ds.ContentTime = time.strftime('%H%M%S')
ds.add_new(private_tag,'OB', payload)
ds.save_as(filename)
示例5: testSetNewDataElementByName
def testSetNewDataElementByName(self):
"""Dataset: set new data_element by name............................."""
ds = Dataset()
ds.TreatmentMachineName = "unit #1"
data_element = ds[0x300a, 0x00b2]
self.assertEqual(data_element.value, "unit #1", "Unable to set data_element by name")
self.assertEqual(data_element.VR, "SH", "data_element not the expected VR")
示例6: OnReceiveStore
def OnReceiveStore(self, SOPClass, DS):
# sleep(0.1)
rl.info('Received C-STORE')
# do something with dataset. For instance, store it on disk.
file_meta = Dataset()
file_meta.MediaStorageSOPClassUID = DS.SOPClassUID
file_meta.MediaStorageSOPInstanceUID = UID.generate_uid() #DS.SOPInstanceUID # !! Need valid UID here
file_meta.ImplementationClassUID = UID.pydicom_root_UID #"1.2.3.4" # !!! Need valid UIDs here
file_path = directory.joinPath([self.StorePath, str(DS.SeriesDate), str(DS.SeriesDescription)])
if fmriQA.is_dicom_dict_QA(DS):
directory.createPath(file_path)
filename = directory.joinPath([file_path, "I%05d" % DS.get('InstanceNumber') + '.'+config.DATA_EXT])
ds = FileDataset(filename, {}, file_meta=file_meta, preamble="\0" * 128)
ds.update(DS)
ds.is_little_endian = True
ds.is_implicit_VR = True
# print ds - prints all DICOM tags contained in the file prior its saving
ds.save_as(filename)
if directory.isFile(filename):
rl.info('File %s written' % filename)
# must return appropriate status
return SOPClass.Success
else:
return SOPClass.UnableToProcess
rl.error('File %s failed to write' % filename)
else:
return SOPClass.IdentifierDoesNotMatchSOPClass
rl.warning('The sent file was not recognised as QA file (%s)' % filename)
示例7: read_partial
def read_partial(fileobj, stop_when=None, defer_size=None, force=False):
"""Parse a DICOM file until a condition is met
``read_partial`` is normally not called directly. Use ``read_file``
instead, unless you need to stop on some condition
other than reaching pixel data.
:arg fileobj: a file-like object. This function does not close it.
:arg stop_when: a callable which takes tag, VR, length,
and returns True or False.
If stop_when returns True,
read_data_element will raise StopIteration.
If None (default), then the whole file is read.
:returns: a set instance
"""
# Read preamble -- raise an exception if missing and force=False
preamble = read_preamble(fileobj, force)
file_meta_dataset = Dataset()
# Assume a transfer syntax, correct it as necessary
is_implicit_VR = True
is_little_endian = True
if preamble:
file_meta_dataset = _read_file_meta_info(fileobj)
transfer_syntax = file_meta_dataset.TransferSyntaxUID
if transfer_syntax == dicom.UID.ImplicitVRLittleEndian:
pass
elif transfer_syntax == dicom.UID.ExplicitVRLittleEndian:
is_implicit_VR = False
elif transfer_syntax == dicom.UID.ExplicitVRBigEndian:
is_implicit_VR = False
is_little_endian = False
elif transfer_syntax == dicom.UID.DeflatedExplicitVRLittleEndian:
# See PS3.6-2008 A.5 (p 71)
# when written, the entire dataset following
# the file metadata was prepared the normal way,
# then "deflate" compression applied.
# All that is needed here is to decompress and then
# use as normal in a file-like object
zipped = fileobj.read()
# -MAX_WBITS part is from comp.lang.python answer:
# groups.google.com/group/comp.lang.python/msg/e95b3b38a71e6799
unzipped = zlib.decompress(zipped, -zlib.MAX_WBITS)
fileobj = BytesIO(unzipped) # a file-like object
is_implicit_VR = False
else:
# Any other syntax should be Explicit VR Little Endian,
# e.g. all Encapsulated (JPEG etc) are ExplVR-LE
# by Standard PS 3.5-2008 A.4 (p63)
is_implicit_VR = False
else: # no header -- use the is_little_endian, implicit assumptions
file_meta_dataset.TransferSyntaxUID = dicom.UID.ImplicitVRLittleEndian
try:
dataset = read_dataset(fileobj, is_implicit_VR, is_little_endian,
stop_when=stop_when, defer_size=defer_size)
except EOFError as e:
pass # error already logged in read_dataset
return FileDataset(fileobj, dataset, preamble, file_meta_dataset,
is_implicit_VR, is_little_endian)
示例8: testSetNonDicom
def testSetNonDicom(self):
"""Dataset: can set class instance property (non-dicom)............."""
ds = Dataset()
ds.SomeVariableName = 42
has_it = hasattr(ds, 'SomeVariableName')
self.assertTrue(has_it, "Variable did not get created")
if has_it:
self.assertEqual(ds.SomeVariableName, 42, "There, but wrong value")
示例9: write_dicom
def write_dicom(pixel_array, filename, ds_copy, ds_ori, volume_number,
series_number, sop_id):
"""Write data in dicom file and copy the header from different dicoms.
:param pixel_array: data to write in a dicom
:param filename: file name for the dicom
:param ds_copy: pydicom object of the dicom to copy info from
:param ds_ori: pydicom object of the dicom where the array comes from
:param volume_number: numero of volume being processed
:param series_number: number of the series being written
:param sop_id: SOPID for the dicom
:return: None
"""
# Set to zero negatives values in the image:
pixel_array[pixel_array < 0] = 0
# Set the DICOM dataset
file_meta = Dataset()
file_meta.MediaStorageSOPClassUID = 'Secondary Capture Image Storage'
file_meta.MediaStorageSOPInstanceUID = ds_ori.SOPInstanceUID
file_meta.ImplementationClassUID = ds_ori.SOPClassUID
ds = FileDataset(filename, {}, file_meta=file_meta, preamble="\0"*128)
# Copy the tag from the original DICOM
for tag, value in ds_ori.items():
if tag != ds_ori.data_element("PixelData").tag:
ds[tag] = value
# Other tags to set
ds.SeriesNumber = series_number
ds.SeriesDescription = ds_ori.SeriesDescription + ' reg_f3d'
sop_uid = sop_id + str(datetime.datetime.now()).replace('-', '')\
.replace(':', '')\
.replace('.', '')\
.replace(' ', '')
ds.SOPInstanceUID = sop_uid[:-1]
ds.ProtocolName = ds_ori.ProtocolName
ds.InstanceNumber = volume_number+1
# Copy from T2 the orientation tags:
ds.PatientPosition = ds_copy.PatientPosition
ds[0x18, 0x50] = ds_copy[0x18, 0x50] # Slice Thicknes
ds[0x18, 0x88] = ds_copy[0x18, 0x88] # Spacing Between Slices
ds[0x18, 0x1312] = ds_copy[0x18, 0x1312] # In-plane Phase Encoding
ds[0x20, 0x32] = ds_copy[0x20, 0x32] # Image Position
ds[0x20, 0x37] = ds_copy[0x20, 0x37] # Image Orientation
ds[0x20, 0x1041] = ds_copy[0x20, 0x1041] # Slice Location
ds[0x28, 0x10] = ds_copy[0x28, 0x10] # rows
ds[0x28, 0x11] = ds_copy[0x28, 0x11] # columns
ds[0x28, 0x30] = ds_copy[0x28, 0x30] # Pixel spacing
# Set the Image pixel array
if pixel_array.dtype != np.uint16:
pixel_array = pixel_array.astype(np.uint16)
ds.PixelData = pixel_array.tostring()
# Save the image
ds.save_as(filename)
示例10: WriteDICOM_slice
def WriteDICOM_slice(self, pixel_array,filename, itemnumber=0, PhotometricInterpretation="MONOCHROME2"):
from dicom.dataset import Dataset, FileDataset
import numpy as np
import datetime, time
"""
INPUTS:
pixel_array: 2D numpy ndarray. If pixel_array is larger than 2D, errors.
filename: string name for the output file.
"""
## This code block was taken from the output of a MATLAB secondary
## capture. I do not know what the long dotted UIDs mean, but
## this code works.
file_meta = Dataset()
file_meta.MediaStorageSOPClassUID = 'Secondary Capture Image Storage'
file_meta.MediaStorageSOPInstanceUID = '1.3.6.1.4.1.9590.100.1.1.111165684411017669021768385720736873780'
file_meta.ImplementationClassUID = '1.3.6.1.4.1.9590.100.1.0.100.4.0'
ds = FileDataset(filename, {},file_meta = file_meta,preamble="\0"*128)
ds.Modality = 'WSD'
ds.ContentDate = str(datetime.date.today()).replace('-','')
ds.ContentTime = str(time.time()) #milliseconds since the epoch
ds.StudyInstanceUID = '1.3.6.1.4.1.9590.100.1.1.124313977412360175234271287472804872093'
ds.SeriesInstanceUID = '1.3.6.1.4.1.9590.100.1.1.369231118011061003403421859172643143649'
ds.SOPInstanceUID = '1.3.6.1.4.1.9590.100.1.1.111165684411017669021768385720736873780'
ds.SOPClassUID = 'Secondary Capture Image Storage'
ds.SecondaryCaptureDeviceManufctur = 'Python 2.7.3'
## These are the necessary imaging components of the FileDataset object.
ds.SamplesPerPixel = 1
if PhotometricInterpretation=="MONOCHROME2":
ds.PhotometricInterpretation = "MONOCHROME2"
ds.PixelRepresentation = 0
ds.HighBit = 15
ds.BitsStored = 16
ds.BitsAllocated = 16
ds.SmallestImagePixelValue = '\\x00\\x00'
ds.LargestImagePixelValue = '\\xff\\xff'
elif PhotometricInterpretation=="RGB":
ds.PhotometricInterpretation = "MONOCHROME2"
ds.PixelRepresentation = 0
ds.HighBit = 15
ds.BitsStored = 16
ds.BitsAllocated = 16
ds.SmallestImagePixelValue = '\\x00\\x00'
ds.LargestImagePixelValue = '\\xff\\xff'
pixel_array = pixel_array[0]
print pixel_array.shape
ds.Columns = pixel_array.shape[0]
ds.ItemNumber = str(itemnumber)
ds.InstanceNumber = str(itemnumber)
ds.SliceLocation = str(itemnumber)
ds.Rows = pixel_array.shape[1]
if pixel_array.dtype != np.uint16:
pixel_array = pixel_array.astype(np.uint16)
ds.PixelData = pixel_array.tostring()
ds.save_as(filename)
return filename
示例11: testTagExceptionPrint
def testTagExceptionPrint(self):
# When printing datasets, a tag number should appear in error
# messages
ds = Dataset()
ds.PatientID = "123456" # Valid value
ds.SmallestImagePixelValue = 0 # Invalid value
expected_msg = "Invalid tag (0028, 0106): object of type 'int' has no len()"
self.failUnlessExceptionArgs(expected_msg, TypeError, lambda: str(ds))
示例12: testValidAssignment
def testValidAssignment(self):
"""Sequence: ensure ability to assign a Dataset to a Sequence item"""
ds = Dataset()
ds.add_new((1,1), 'IS', 1)
# Create a single element Sequence first
seq = Sequence([Dataset(),])
seq[0] = ds
self.assertEqual(seq[0], ds, "Dataset modified during assignment")
示例13: testAttributeErrorInProperty
def testAttributeErrorInProperty(self):
"""Dataset: AttributeError in property raises actual error message..."""
# This comes from bug fix for issue 42
# First, fake enough to try the pixel_array property
ds = Dataset()
ds.file_meta = Dataset()
ds.PixelData = 'xyzlmnop'
attribute_error_msg = "AttributeError in pixel_array property: " + \
"Dataset does not have attribute 'TransferSyntaxUID'"
self.failUnlessExceptionArgs(attribute_error_msg,
PropertyError, ds._get_pixel_array)
示例14: testValidInitialization
def testValidInitialization(self):
"""Sequence: Ensure valid creation of Sequences using Dataset inputs"""
inputs = { 'PatientPosition':'HFS',
'PatientSetupNumber':'1',
'SetupTechniqueDescription':''}
patientSetups = Dataset()
patientSetups.update(inputs)
# Construct the sequence
seq = Sequence((patientSetups,))
self.assert_(isinstance(seq[0], Dataset),
"Dataset modified during Sequence creation")
示例15: testTagExceptionWalk
def testTagExceptionWalk(self):
# When recursing through dataset, a tag number should appear in
# error messages
ds = Dataset()
ds.PatientID = "123456" # Valid value
ds.SmallestImagePixelValue = 0 # Invalid value
expected_msg = "Invalid tag (0028, 0106): object of type 'int' has no len()"
callback = lambda dataset, data_element: str(data_element)
func = lambda: ds.walk(callback)
self.failUnlessExceptionArgs(expected_msg, TypeError, func)