def testValuesIdentical(self): """Deferred values exactly matches normal read...............""" ds_norm = read_file(self.testfile_name) ds_defer = read_file(self.testfile_name, defer_size=2000) for data_elem in ds_norm: tag = data_elem.tag self.assertEqual(data_elem.value, ds_defer[tag].value, "Mismatched value for tag %r" % tag)
def testPrivateSQ(self): """Can read private undefined length SQ without error....................""" # From issues 91, 97, 98. Bug introduced by fast reading, due to VR=None # in raw data elements, then an undefined length private item VR is looked up, # and there is no such tag, generating an exception # Simply read the file, in 0.9.5 this generated an exception read_file(priv_SQ_name)
def testNoPixelsRead(self): """Returns all data elements before pixels using stop_before_pixels=False""" # Just check the tags, and a couple of values ctpartial = read_file(ct_name, stop_before_pixels=True) ctpartial_tags = sorted(ctpartial.keys()) ctfull = read_file(ct_name) ctfull_tags = sorted(ctfull.keys()) msg = "Tag list of partial CT read (except pixel tag and padding) did not match full read" msg += "\nExpected: %r\nGot %r" % (ctfull_tags[:-2], ctpartial_tags) missing = [Tag(0x7fe0, 0x10), Tag(0xfffc, 0xfffc)] self.assertEqual(ctfull_tags, ctpartial_tags + missing, msg)
def testReadFileGivenFileObject(self): """filereader: can read using already opened file............""" f = open(ct_name, "rb") ct = read_file(f) # Tests here simply repeat testCT -- perhaps should collapse the code together? got = ct.ImagePositionPatient DS = dicom.valuerep.DS expected = [DS("-158.135803"), DS("-179.035797"), DS("-75.699997")] self.assertTrue(got == expected, "ImagePosition(Patient) values not as expected") self.assertEqual( ct.file_meta.ImplementationClassUID, "1.3.6.1.4.1.5962.2", "ImplementationClassUID not the expected value" ) self.assertEqual( ct.file_meta.ImplementationClassUID, ct.file_meta[0x2, 0x12].value, "ImplementationClassUID does not match the value accessed by tag number", ) # (0020, 0032) Image Position (Patient) [-158.13580300000001, -179.035797, -75.699996999999996] got = ct.ImagePositionPatient expected = [DS("-158.135803"), DS("-179.035797"), DS("-75.699997")] self.assertTrue(got == expected, "ImagePosition(Patient) values not as expected") self.assertEqual(ct.Rows, 128, "Rows not 128") self.assertEqual(ct.Columns, 128, "Columns not 128") self.assertEqual(ct.BitsStored, 16, "Bits Stored not 16") self.assertEqual(len(ct.PixelData), 128 * 128 * 2, "Pixel data not expected length") # Should also be able to close the file ourselves without exception raised: f.close()
def testNestedPrivateSQ(self): """Can successfully read a private SQ which contains additional SQ's.....""" # From issue 113. When a private SQ of undefined length is used, the # sequence is read in and the length of the SQ is determined upon # identification of the SQ termination sequence. When using nested # Sequences, the first termination sequence encountered actually # belongs to the nested Sequence not the parent, therefore the # remainder of the file is not read in properly ds = read_file(nested_priv_SQ_name) # Make sure that the entire dataset was read in pixel_data_tag = TupleTag((0x7FE0, 0x10)) self.assertTrue(pixel_data_tag in ds, "Entire dataset was not parsed properly. PixelData is not present") # Check that the DataElement is indeed a Sequence tag = TupleTag((0x01, 0x01)) seq0 = ds[tag] self.assertEqual(seq0.VR, "SQ", "First level sequence not parsed properly") # Now verify the presence of the nested private SQ seq1 = seq0[0][tag] self.assertEqual(seq1.VR, "SQ", "Second level sequence not parsed properly") # Now make sure the values that are parsed are correct got = seq1[0][tag].value expected = b"Double Nested SQ" self.assertEqual(got, expected, "Expected a value of %s, got %s'" % (expected, got)) got = seq0[0][0x01, 0x02].value expected = b"Nested SQ" self.assertEqual(got, expected, "Expected a value of %s, got %s'" % (expected, got))
def testCT(self): """Returns correct values for sample data elements in test CT file....""" ct = read_file(ct_name) self.assertEqual(ct.file_meta.ImplementationClassUID, '1.3.6.1.4.1.5962.2', "ImplementationClassUID not the expected value") self.assertEqual(ct.file_meta.ImplementationClassUID, ct.file_meta[0x2, 0x12].value, "ImplementationClassUID does not match the value accessed by tag number") # (0020, 0032) Image Position (Patient) [-158.13580300000001, -179.035797, -75.699996999999996] got = ct.ImagePositionPatient DS = dicom.valuerep.DS expected = [DS('-158.135803'), DS('-179.035797'), DS('-75.699997')] self.assertTrue(got == expected, "ImagePosition(Patient) values not as expected." "got {0}, expected {1}".format(got, expected)) self.assertEqual(ct.Rows, 128, "Rows not 128") self.assertEqual(ct.Columns, 128, "Columns not 128") self.assertEqual(ct.BitsStored, 16, "Bits Stored not 16") self.assertEqual(len(ct.PixelData), 128 * 128 * 2, "Pixel data not expected length") # Also test private elements name can be resolved: expected = "[Duration of X-ray on]" got = ct[(0x0043, 0x104e)].name msg = "Mismatch in private tag name, expected '%s', got '%s'" self.assertEqual(expected, got, msg % (expected, got)) # Check that can read pixels - get last one in array if have_numpy: expected = 909 got = ct.pixel_array[-1][-1] msg = "Did not get correct value for last pixel: expected %d, got %r" % (expected, got) self.assertEqual(expected, got, msg) else: print "**Numpy not available -- pixel array test skipped**"
def testRTstruct(self): """Returns correct values for sample elements in test RTSTRUCT file....""" # RTSTRUCT test file has complex nested sequences -- see rtstruct.dump file # Also has no DICOM header ... so tests 'force' argument of read_file rtss = read_file(rtstruct_name, force=True) expected = '1.2.840.10008.1.2' # implVR little endian got = rtss.file_meta.TransferSyntaxUID msg = "Expected transfer syntax %r, got %r" % (expected, got) self.assertEqual(expected, got, msg) frame_of_ref = rtss.ReferencedFrameOfReferenceSequence[0] study = frame_of_ref.RTReferencedStudySequence[0] uid = study.RTReferencedSeriesSequence[0].SeriesInstanceUID expected = "1.2.826.0.1.3680043.8.498.2010020400001.2.1.1" msg = "Expected Reference Series UID '%s', got '%s'" % (expected, uid) self.assertEqual(expected, uid, msg) got = rtss.ROIContourSequence[0].ContourSequence[2].ContourNumber expected = 3 msg = "Expected Contour Number %d, got %r" % (expected, got) self.assertEqual(expected, got, msg) obs_seq0 = rtss.RTROIObservationsSequence[0] got = obs_seq0.ROIPhysicalPropertiesSequence[0].ROIPhysicalProperty expected = 'REL_ELEC_DENSITY' msg = "Expected Physical Property '%s', got %r" % (expected, got) self.assertEqual(expected, got, msg)
def testDir(self): """Returns correct dir attributes for both Dataset and DICOM names (python >= 2.6)..""" # Only python >= 2.6 calls __dir__ for dir() call rtss = read_file(rtstruct_name, force=True) # sample some expected 'dir' values got_dir = dir(rtss) expect_in_dir = [ 'pixel_array', 'add_new', 'ROIContourSequence', 'StructureSetDate', '__sizeof__' ] expect_not_in_dir = ['RemovePrivateTags', 'AddNew', 'GroupDataset'] # remove in v1.0 for name in expect_in_dir: self.assertTrue(name in got_dir, "Expected name '%s' in dir()" % name) for name in expect_not_in_dir: self.assertTrue(name not in got_dir, "Unexpected name '%s' in dir()" % name) # Now check for some items in dir() of a nested item roi0 = rtss.ROIContourSequence[0] got_dir = dir(roi0) expect_in_dir = [ 'pixel_array', 'add_new', 'ReferencedROINumber', 'ROIDisplayColor', '__sizeof__' ] for name in expect_in_dir: self.assertTrue(name in got_dir, "Expected name '%s' in dir()" % name)
def testDeflate(self): """Returns correct values for sample data elements in test compressed (zlib deflate) file""" # Everything after group 2 is compressed. If we can read anything else, the decompression must have been ok. ds = read_file(deflate_name) got = ds.ConversionType expected = "WSD" self.assertEqual(got, expected, "Attempted to read deflated file data element Conversion Type, expected '%s', got '%s'" % (expected, got))
def testReadFileGivenFileObject(self): """filereader: can read using already opened file............""" f = open(ct_name, 'rb') ct = read_file(f) # Tests here simply repeat testCT -- perhaps should collapse the code together? got = ct.ImagePositionPatient DS = dicom.valuerep.DS expected = [DS('-158.135803'), DS('-179.035797'), DS('-75.699997')] self.assertTrue(got == expected, "ImagePosition(Patient) values not as expected") self.assertEqual(ct.file_meta.ImplementationClassUID, '1.3.6.1.4.1.5962.2', "ImplementationClassUID not the expected value") self.assertEqual( ct.file_meta.ImplementationClassUID, ct.file_meta[0x2, 0x12].value, "ImplementationClassUID does not match the value accessed by tag number" ) # (0020, 0032) Image Position (Patient) [-158.13580300000001, -179.035797, -75.699996999999996] got = ct.ImagePositionPatient expected = [DS('-158.135803'), DS('-179.035797'), DS('-75.699997')] self.assertTrue(got == expected, "ImagePosition(Patient) values not as expected") self.assertEqual(ct.Rows, 128, "Rows not 128") self.assertEqual(ct.Columns, 128, "Columns not 128") self.assertEqual(ct.BitsStored, 16, "Bits Stored not 16") self.assertEqual(len(ct.PixelData), 128 * 128 * 2, "Pixel data not expected length") # Should also be able to close the file ourselves without exception raised: f.close()
def testCT(self): """Returns correct values for sample data elements in test CT file....""" ct = read_file(ct_name) self.assertEqual(ct.file_meta.ImplementationClassUID, '1.3.6.1.4.1.5962.2', "ImplementationClassUID not the expected value") self.assertEqual(ct.file_meta.ImplementationClassUID, ct.file_meta[0x2, 0x12].value, "ImplementationClassUID does not match the value accessed by tag number") # (0020, 0032) Image Position (Patient) [-158.13580300000001, -179.035797, -75.699996999999996] got = ct.ImagePositionPatient DS = dicom.valuerep.DS expected = [DS('-158.135803'), DS('-179.035797'), DS('-75.699997')] self.assertTrue(got == expected, "ImagePosition(Patient) values not as expected." "got {0}, expected {1}".format(got, expected)) self.assertEqual(ct.Rows, 128, "Rows not 128") self.assertEqual(ct.Columns, 128, "Columns not 128") self.assertEqual(ct.BitsStored, 16, "Bits Stored not 16") self.assertEqual(len(ct.PixelData), 128 * 128 * 2, "Pixel data not expected length") # Also test private elements name can be resolved: expected = "[Duration of X-ray on]" got = ct[(0x0043, 0x104e)].name msg = "Mismatch in private tag name, expected '%s', got '%s'" self.assertEqual(expected, got, msg % (expected, got)) # Check that can read pixels - get last one in array if have_numpy: expected = 909 got = ct.pixel_array[-1][-1] msg = "Did not get correct value for last pixel: expected %d, got %r" % (expected, got) self.assertEqual(expected, got, msg) else: print("**Numpy not available -- pixel array test skipped**")
def testFileExists(self): """Deferred read raises error if file no longer exists.....""" ds = read_file(self.testfile_name, defer_size=2000) os.remove(self.testfile_name) def read_value(): data_elem = ds.PixelData self.assertRaises(IOError, read_value)
def testMR(self): """Returns correct values for sample data elements in test MR file.....""" mr = read_file(mr_name) # (0010, 0010) Patient's Name 'CompressedSamples^MR1' self.assertEqual(mr.PatientsName, 'CompressedSamples^MR1', "Wrong patient name") self.assertEqual(mr.PatientsName, mr[0x10,0x10].value, "Name does not match value found when accessed by tag number") self.assert_(isClose(mr.PixelSpacing, [0.3125, 0.3125]), "Wrong pixel spacing")
def testZippedDeferred(self): """Deferred values from a gzipped file works..............""" # Arose from issue 103 "Error for defer_size read of gzip file object" fobj = gzip.open(gzip_name) ds = read_file(fobj, defer_size=1) # before the fix, this threw an error as file reading was not in right place, # it was re-opened as a normal file, not zip file num = ds.InstanceNumber
def testListItemWriteBack(self): """Change item in a list and confirm it is written to file ..""" DS_expected = 0 CS_expected = "new" SS_expected = 999 ds = read_file(ct_name) ds.ImagePositionPatient[2] = DS_expected ds.ImageType[1] = CS_expected ds[(0x0043, 0x1012)].value[0] = SS_expected ds.save_as(ct_out) # Now read it back in and check that the values were changed ds = read_file(ct_out) self.assert_(ds.ImageType[1] == CS_expected, "Item in a list not written correctly to file (VR=CS)") self.assert_(ds[0x00431012].value[0] == SS_expected, "Item in a list not written correctly to file (VR=SS)") self.assert_(ds.ImagePositionPatient[2] == DS_expected, "Item in a list not written correctly to file (VR=DS)") if os.path.exists(ct_out): os.remove(ct_out)
def compare(self, in_, out_): """Read file1, write file2, then compare. Return value as for files_identical""" dataset = read_file(in_) write_file(out_, dataset) same, pos = files_identical(in_, out_) self.assert_(same, "Files are not identical - first difference at 0x%x" % pos) if os.path.exists(out_): os.remove(out_) # get rid of the file
def image_processing(file, value, rect_mask, circle_mask, len_files): """ Do the processing of an image to obtain the skull. """ line = currentframe().f_back.f_lineno if file.__class__ != str: print 'Line', line, '- Error: First argument must be str.' exit() elif value.__class__ != int: print 'Line', line, '- Error: Second argument must be int.' exit() else: plt.close('all') image_begin_time = time.time() # ---------------------------- # ----- 1. DICOM OPENING ----- # ---------------------------- dicom_file = dicomio.read_file(file) dicom_array = dicom_file.pixel_array image_number = dicom_file.InstanceNumber if image_number < 10: image_number = '0000' + str(image_number) if image_number >= 10 and image_number < 100: image_number = '000' + str(image_number) if image_number >= 100 and image_number < 1000: image_number = '00' + str(image_number) if image_number >= 1000: image_number = '0' + str(image_number) # Two ways to give back the initial dimensions to the segmented images: # - Use the MedPy library which seems really easy to use, but which does not work now # Website: https://pypi.python.org/pypi/MedPy # - Use the Pydicom library with .PixelSpacing, which seems to be a bit more difficult to use # Website: https://pyscience.wordpress.com/2014/09/08/dicom-in-python-importing-medical-image-data-into-numpy-with-pydicom-and-vtk/ #pixel_dims = (int(dicom_file.Rows), int(dicom_file.Columns), len_files) pixel_spacing = [float(dicom_file.PixelSpacing[0]), float(dicom_file.PixelSpacing[1]), float(dicom_file.SliceThickness)] # print 'slice_thickness :', float(dicom_file.SliceThickness) new_dicom_array = normalize(dicom_array) new_dicom_array2 = convert_from_uint16_to_uint8(normalize(double_threshold(new_dicom_array, value, int(array_max(new_dicom_array))))) # Value was equal to 2200 for the skull only, and 1500 seems 'good' for "living persons". grayskull_image = array2image(new_dicom_array2) skull_array = threshold(new_dicom_array2, 1) skull_image = array2image(skull_array) image_end_time = time.time() print 'Image execution time:', round(image_end_time - image_begin_time, 3), 'seconds' return grayskull_image, skull_image, pixel_spacing, image_number
def testNoMetaGroupLength(self): """Read file with no group length in file meta...........................""" # Issue 108 -- iView example file with no group length (0002,0002) # Originally crashed, now check no exception, but also check one item # in file_meta, and second one in followinsg dataset ds = read_file(no_meta_group_length) got = ds.InstanceCreationDate expected = "20111130" self.assertEqual(got, expected, "Sample data element after file meta with no group length failed, expected '%s', got '%s'" % (expected, got))
def compare(self, in_filename, out_filename): """Read file1, write file2, then compare. Return value as for files_identical""" dataset = read_file(in_filename) dataset.save_as(out_filename) same, pos = files_identical(in_filename, out_filename) self.assert_( same, "Files are not identical - first difference at 0x%x" % pos) if os.path.exists(out_filename): os.remove(out_filename) # get rid of the file
def testMR(self): """Returns correct values for sample data elements in test MR file.....""" mr = read_file(mr_name) # (0010, 0010) Patient's Name 'CompressedSamples^MR1' self.assertEqual(mr.PatientName, 'CompressedSamples^MR1', "Wrong patient name") self.assertEqual(mr.PatientName, mr[0x10, 0x10].value, "Name does not match value found when accessed by tag number") got = mr.PixelSpacing expected = [Decimal('0.3125'), Decimal('0.3125')] self.assertTrue(got == expected, "Wrong pixel spacing")
def testReadFileGivenFileLikeObject(self): """filereader: can read using a file-like (BytesIO) file....""" file_like = BytesIO(open(ct_name, 'rb').read()) ct = read_file(file_like) # Tests here simply repeat some of testCT test got = ct.ImagePositionPatient expected = [Decimal('-158.135803'), Decimal('-179.035797'), Decimal('-75.699997')] self.assertTrue(got == expected, "ImagePosition(Patient) values not as expected") self.assertEqual(len(ct.PixelData), 128 * 128 * 2, "Pixel data not expected length") # Should also be able to close the file ourselves without exception raised: file_like.close()
def testTimeCheck(self): """Deferred read warns if file has been modified...........""" if stat_available: ds = read_file(self.testfile_name, defer_size=2000) from time import sleep sleep(1) open(self.testfile_name, "r+").write('\0') # "touch" the file warning_start = "Deferred read warning -- file modification time " def read_value(): data_elem = ds.PixelData assertWarns(self, warning_start, read_value)
def compare(self, in_filename, out_filename): """Read file1, write file2, then compare. Return value as for files_identical. """ dataset = read_file(in_filename) dataset.save_as(out_filename) same, pos = files_identical(in_filename, out_filename) self.assertTrue(same, "Files are not identical - first difference at 0x%x" % pos) if os.path.exists(out_filename): os.remove(out_filename) # get rid of the file
def testReadFileGivenFileLikeObject(self): """filereader: can read using a file-like (StringIO) file....""" file_like = StringIO(open(ct_name, 'rb').read()) ct = read_file(file_like) # Tests here simply repeat some of testCT test imagepos = ct.ImagePositionPatient self.assert_(isClose(imagepos, [-158.135803, -179.035797, -75.699997]), "ImagePosition(Patient) values not as expected") self.assertEqual(len(ct.PixelData), 128*128*2, "Pixel data not expected length") # Should also be able to close the file ourselves without exception raised: file_like.close()
def testRTDose(self): """Returns correct values for sample data elements in test RT Dose file""" dose = read_file(rtdose_name) self.assertEqual(dose.FrameIncrementPointer, Tag((0x3004, 0x000c)), "Frame Increment Pointer not the expected value") self.assertEqual(dose.FrameIncrementPointer, dose[0x28, 9].value, "FrameIncrementPointer does not match the value accessed by tag number") # try a value that is nested the deepest (so deep I break it into two steps!) fract = dose.ReferencedRTPlanSequence[0].ReferencedFractionGroupSequence[0] beamnum = fract.ReferencedBeamSequence[0].ReferencedBeamNumber self.assertEqual(beamnum, 1, "Beam number not the expected value")
def testMR(self): """Returns correct values for sample data elements in test MR file.....""" mr = read_file(mr_name) # (0010, 0010) Patient's Name 'CompressedSamples^MR1' self.assertEqual(mr.PatientName, 'CompressedSamples^MR1', "Wrong patient name") self.assertEqual( mr.PatientName, mr[0x10, 0x10].value, "Name does not match value found when accessed by tag number") got = mr.PixelSpacing expected = [Decimal('0.3125'), Decimal('0.3125')] self.assert_(got == expected, "Wrong pixel spacing")
def testReadFileGivenFileLikeObject(self): """filereader: can read using a file-like (BytesIO) file....""" with open(ct_name, 'rb') as f: file_like = BytesIO(f.read()) ct = read_file(file_like) # Tests here simply repeat some of testCT test got = ct.ImagePositionPatient DS = dicom.valuerep.DS expected = [DS('-158.135803'), DS('-179.035797'), DS('-75.699997')] self.assertTrue(got == expected, "ImagePosition(Patient) values not as expected") self.assertEqual(len(ct.PixelData), 128 * 128 * 2, "Pixel data not expected length") # Should also be able to close the file ourselves without exception raised: file_like.close()
def testRTPlan(self): """Returns correct values for sample data elements in test RT Plan file""" plan = read_file(rtplan_name) beam = plan.Beams[0] cp0, cp1 = beam.ControlPoints # if not two controlpoints, then this would raise exception self.assertEqual(beam.TreatmentMachineName, "unit001", "Incorrect unit name") self.assertEqual(beam.TreatmentMachineName, beam[0x300a, 0x00b2].value, "beam TreatmentMachineName does not match the value accessed by tag number") cumDoseRef = cp1.ReferencedDoseReferences[0].CumulativeDoseReferenceCoefficient self.assert_(isClose(cumDoseRef, 0.9990268), "Cum Dose Ref Coeff not the expected value (CP1, Ref'd Dose Ref") JawX = cp0.BLDPositions[0].LeafJawPositions self.assert_(isClose(JawX[0], -100.0) and isClose(JawX[1], 100.0), "X jaws not as expected (control point 0)")
def testRTPlan(self): """Returns correct values for sample data elements in test RT Plan file""" plan = read_file(rtplan_name) beam = plan.BeamSequence[0] cp0, cp1 = beam.ControlPointSequence # if not two controlpoints, then this would raise exception self.assertEqual(beam.TreatmentMachineName, "unit001", "Incorrect unit name") self.assertEqual(beam.TreatmentMachineName, beam[0x300a, 0x00b2].value, "beam TreatmentMachineName does not match the value accessed by tag number") got = cp1.ReferencedDoseReferenceSequence[0].CumulativeDoseReferenceCoefficient expected = Decimal('0.9990268') self.assert_(got == expected, "Cum Dose Ref Coeff not the expected value (CP1, Ref'd Dose Ref") got = cp0.BeamLimitingDevicePositionSequence[0].LeafJawPositions self.assert_(got[0] == Decimal('-100') and got[1] == Decimal('100.0'), "X jaws not as expected (control point 0)")
def testDir(self): """Returns correct dir attributes for both Dataset and DICOM names (python >= 2.6)..""" # Only python >= 2.6 calls __dir__ for dir() call rtss = read_file(rtstruct_name, force=True) # sample some expected 'dir' values got_dir = dir(rtss) expect_in_dir = ["pixel_array", "add_new", "ROIContourSequence", "StructureSetDate", "__sizeof__"] expect_not_in_dir = ["RemovePrivateTags", "AddNew", "GroupDataset"] # remove in v1.0 for name in expect_in_dir: self.assertTrue(name in got_dir, "Expected name '%s' in dir()" % name) for name in expect_not_in_dir: self.assertTrue(name not in got_dir, "Unexpected name '%s' in dir()" % name) # Now check for some items in dir() of a nested item roi0 = rtss.ROIContourSequence[0] got_dir = dir(roi0) expect_in_dir = ["pixel_array", "add_new", "ReferencedROINumber", "ROIDisplayColor", "__sizeof__"] for name in expect_in_dir: self.assertTrue(name in got_dir, "Expected name '%s' in dir()" % name)
def testRTPlan(self): """Returns correct values for sample data elements in test RT Plan file""" plan = read_file(rtplan_name) beam = plan.BeamSequence[0] cp0, cp1 = beam.ControlPointSequence # if not two controlpoints, then this would raise exception self.assertEqual(beam.TreatmentMachineName, "unit001", "Incorrect unit name") self.assertEqual(beam.TreatmentMachineName, beam[0x300a, 0x00b2].value, "beam TreatmentMachineName does not match the value accessed by tag number") got = cp1.ReferencedDoseReferenceSequence[0].CumulativeDoseReferenceCoefficient DS = dicom.valuerep.DS expected = DS('0.9990268') self.assertTrue(got == expected, "Cum Dose Ref Coeff not the expected value (CP1, Ref'd Dose Ref") got = cp0.BeamLimitingDevicePositionSequence[0].LeafJawPositions self.assertTrue(got[0] == DS('-100') and got[1] == DS('100.0'), "X jaws not as expected (control point 0)")
def __init__(self, parent=None, flags=Qt.Widget): super(DCMWidget,self).__init__(parent, flags) #self.painter = QPainter(self) self.dcmdata = read_file(filenamec) self.row = self.dcmdata.Rows # width self.column = self.dcmdata.Columns # height self.modality = self.dcmdata.Modality self.slope = self.dcmdata.RescaleSlope self.interceprt = self.dcmdata.RescaleIntercept print 'Rows,Column:',self.row,self.column print 'Modality:',self.modality if type(self.dcmdata.WindowWidth) == dicom.multival.MultiValue: self.winw = self.dcmdata.WindowWidth[0] self.winc = self.dcmdata.WindowCenter[0] else: self.winw = self.dcmdata.WindowWidth self.winc = self.dcmdata.WindowCenter print 'winw,winc:',self.winw,self.winc print 'pixel array shape:',self.dcmdata.pixel_array.shape self.win_width = QApplication.desktop().width() self.win_height = QApplication.desktop().height() self.resize(800, 600) #self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.image = None self.pmin = None self.pmax = None #self.pix = QPixmap(filenameb) self.pixel_array_ori = self.dcmdata.pixel_array*self.slope+self.interceprt self.pixel_array_lut = self.get_LUT_value(self.pixel_array_ori,self.winw,self.winc) self.genImage()
def testDir(self): """Returns correct dir attributes for both Dataset and DICOM names (python >= 2.6)..""" # Only python >= 2.6 calls __dir__ for dir() call if sys.version_info >= (2,6): rtss = read_file(rtstruct_name, force=True) # sample some expected 'dir' values got_dir = dir(rtss) expect_in_dir = ['pixel_array', 'add_new', 'ROIContourSequence', 'StructureSetDate', '__sizeof__'] expect_not_in_dir = ['RemovePrivateTags', 'AddNew', 'GroupDataset'] # remove in v1.0 for name in expect_in_dir: self.assert_(name in got_dir, "Expected name '%s' in dir()" % name) for name in expect_not_in_dir: self.assert_(name not in got_dir, "Unexpected name '%s' in dir()" % name) # Now check for some items in dir() of a nested item roi0 = rtss.ROIContourSequence[0] got_dir = dir(roi0) expect_in_dir = ['pixel_array', 'add_new', 'ReferencedROINumber', 'ROIDisplayColor', '__sizeof__'] for name in expect_in_dir: self.assert_(name in got_dir, "Expected name '%s' in dir()" % name)
def testNestedPrivateSQ(self): """Can successfully read a private SQ which contains additional SQ's.....""" # From issue 113. When a private SQ of undefined length is used, the # sequence is read in and the length of the SQ is determined upon # identification of the SQ termination sequence. When using nested # Sequences, the first termination sequence encountered actually # belongs to the nested Sequence not the parent, therefore the # remainder of the file is not read in properly ds = read_file(nested_priv_SQ_name) # Make sure that the entire dataset was read in pixel_data_tag = TupleTag((0x7fe0, 0x10)) self.assertTrue( pixel_data_tag in ds, "Entire dataset was not parsed properly. PixelData is not present") # Check that the DataElement is indeed a Sequence tag = TupleTag((0x01, 0x01)) seq0 = ds[tag] self.assertEqual(seq0.VR, 'SQ', "First level sequence not parsed properly") # Now verify the presence of the nested private SQ seq1 = seq0[0][tag] self.assertEqual(seq1.VR, 'SQ', "Second level sequence not parsed properly") # Now make sure the values that are parsed are correct got = seq1[0][tag].value expected = b'Double Nested SQ' self.assertEqual(got, expected, "Expected a value of %s, got %s'" % (expected, got)) got = seq0[0][0x01, 0x02].value expected = b'Nested SQ' self.assertEqual(got, expected, "Expected a value of %s, got %s'" % (expected, got))
def data(self): if not self._data: self._data = read_file(self.path) return self._data
def setUp(self): self.jpeg = read_file(jpeg_lossless_name)
def setUp(self): self.jpeg = read_file(jpeg2000_name)
def __initialized(self): try: header = read_file(self.__filename, defer_size=None, stop_before_pixels=True, force=True) except InvalidDicomError: self.__isDicom = False return try: # find the manufacturer self.__manufacturer = 'UNKNOWN' if 'Manufacturer' in header: for manufacturer in manufacturers: if manufacturer in header.Manufacturer: self.__manufacturer = manufacturer self.__patientName = util.slugify(header.PatientName) self.__seriesDescription = util.slugify(header.SeriesDescription) self.__seriesNumber = header.SeriesNumber self.__instanceNumber = header.InstanceNumber self.__mrModel = header.ManufacturerModelName self.__magneticFieldStrength = header.MagneticFieldStrength self.__studyUID = header.StudyInstanceUID self.__tr = float(header.RepetitionTime) # TR Repetition Time self.__te = float(header.EchoTime) # TE Echo Time self.__flipAngle = float(header.FlipAngle) # Flip Angle self.__matrixSize = [ value for value in header.AcquisitionMatrix if value != 0 ] # Matrix Size self.__voxelSize = map( float, [ header.PixelSpacing[0], # Voxel size header.PixelSpacing[1], header.SliceThickness ]) self.__fov = self.__matrixSize[0] * self.__voxelSize[ 0] # Compute FOV self.__isDicom = True except AttributeError as a: if "EchoTime" in a.message: try: self.__te = header[Tag((0x2001, 0x1025))].value self.__isDicom = True except KeyError as k: self.__isDicom = False else: self.__isDicom = False if self.isSiemens(): if 'DIFFUSION' and 'MOSAIC' in header.ImageType: # If Diffusion Acquistion self.__SequenceName = 'Diffusion' elif 'DIFFUSION' in header.ImageType: # If b0 Acquistion self.__SequenceName = 'b0' elif 'M' and 'NORM' in header.ImageType: # If T1 Acquisition self.__SequenceName = 'Structural T1' self.__ti = float(header.InversionTime) elif 'P' in header.ImageType: # If Phase acquisition self.__SequenceName = 'Phase' else: # If Magnitude acquisition self.__SequenceName = 'Magnitude' # inherith Siemens ascconv properties Ascconv.__init__(self, self.__filename) bandwidthPerPixelPhaseEncodeTag = Tag((0x0019, 0x1028)) try: if header.has_key(bandwidthPerPixelPhaseEncodeTag): val = header[bandwidthPerPixelPhaseEncodeTag].value try: self.__bandwidthPerPixelPhaseEncode = float(val) except ValueError: # some data have wrong VR in dicomparser, try to unpack self.__bandwidthPerPixelPhaseEncode = struct.unpack( 'd', val)[0] self.__echoSpacing = 1 / (self.__bandwidthPerPixelPhaseEncode * self.getEpiFactor()) * 1000.0 * \ self.getPatFactor() * self.getPhaseResolution() * \ self.getPhaseOversampling() except (KeyError, IndexError, TypeError, ValueError): self.__echoSpacing = None
def __initialized(self): try: header = read_file(self.__filename, defer_size=None, stop_before_pixels=True, force=True) except InvalidDicomError: self.__isDicom = False return try: # find the manufacturer self.__manufacturer = 'UNKNOWN' if 'Manufacturer' in header: for manufacturer in manufacturers: if manufacturer in header.Manufacturer: self.__manufacturer = manufacturer self.__patientName = util.slugify(header.PatientName) self.__seriesDescription = util.slugify(header.SeriesDescription) self.__seriesNumber = header.SeriesNumber self.__instanceNumber = header.InstanceNumber self.__mrModel = header.ManufacturerModelName self.__magneticFieldStrength = header.MagneticFieldStrength self.__studyUID = header.StudyInstanceUID self.__tr = float(header.RepetitionTime) # TR Repetition Time self.__te = float(header.EchoTime) # TE Echo Time self.__flipAngle = float(header.FlipAngle) # Flip Angle self.__matrixSize = [value for value in header.AcquisitionMatrix if value != 0] # Matrix Size self.__voxelSize = map(float, [header.PixelSpacing[0], # Voxel size header.PixelSpacing[1], header.SliceThickness]) self.__fov = self.__matrixSize[0] * self.__voxelSize[0] # Compute FOV self.__isDicom = True except AttributeError as a: if "EchoTime" in a.message: try: self.__te = header[Tag((0x2001, 0x1025))].value self.__isDicom = True except KeyError as k: self.__isDicom = False else: self.__isDicom = False if self.isSiemens(): if 'DIFFUSION' and 'MOSAIC' in header.ImageType: # If Diffusion Acquistion self.__SequenceName = 'Diffusion' elif 'DIFFUSION' in header.ImageType: # If b0 Acquistion self.__SequenceName = 'b0' elif 'M' and 'NORM' in header.ImageType: # If T1 Acquisition self.__SequenceName = 'Structural T1' self.__ti = float(header.InversionTime) elif 'P' in header.ImageType: # If Phase acquisition self.__SequenceName = 'Phase' else: # If Magnitude acquisition self.__SequenceName = 'Magnitude' # inherith Siemens ascconv properties Ascconv.__init__(self, self.__filename) bandwidthPerPixelPhaseEncodeTag = Tag((0x0019, 0x1028)) try: if header.has_key(bandwidthPerPixelPhaseEncodeTag): val = header[bandwidthPerPixelPhaseEncodeTag].value try: self.__bandwidthPerPixelPhaseEncode = float(val) except ValueError: # some data have wrong VR in dicomparser, try to unpack self.__bandwidthPerPixelPhaseEncode = struct.unpack('d', val)[0] self.__echoSpacing = 1 / (self.__bandwidthPerPixelPhaseEncode * self.getEpiFactor()) * 1000.0 * \ self.getPatFactor() * self.getPhaseResolution() * \ self.getPhaseOversampling() except (KeyError, IndexError, TypeError, ValueError): self.__echoSpacing = None
#logger.setLevel(logging.DEBUG) #dicom.debug(True) #print type(logger.handlers[0]) #H:unsigned short #s:string (array of char) #L:unsigned long #HHL #struct(endian_chr + "HH2sH") #group, elem, VR, length = element_struct_unpack(bytes_read) explict #group, elem, length = element_struct_unpack(bytes_read) implict filename = r'E:\Project\Python\dicom\306.dcm' dcm = read_file(filename) #print dcm[(0x0010, 0x0010)].name #print dcm[(0x0010, 0x0010)].value #dcm.decode() #print dcm.PatientName #print dcm.get_item(key) #print dcm. #print dcm.pixel_array #print dcm.PixelData #print dcm.SamplesPerPixel #print dcm.BitsStored #print dcm.BitsAllocated #print dcm.HighBit #print dcm.SliceLocation #print dcm.SliceThickness #print dcm.PixelRepresentation
def data(self): """Lazy evaluated DICOM file data.""" if not self._data: self._data = read_file(self.path) return self._data