Ejemplo n.º 1
0
 def setUp(self):
     self.jpeg_ls_lossless = read_file(jpeg_ls_lossless_name)
     self.mr_small = read_file(mr_name)
     self.emri_jpeg_ls_lossless = read_file(emri_jpeg_ls_lossless)
     self.emri_small = read_file(emri_name)
     self.original_handlers = pydicom.config.image_handlers
     pydicom.config.image_handlers = [pillow_handler, numpy_handler]
Ejemplo n.º 2
0
 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)
Ejemplo n.º 3
0
 def test_multivalue_DA(self):
     """Write DA/DT/TM data elements.........."""
     multi_DA_expected = (date(1961, 8, 4), date(1963, 11, 22))
     DA_expected = date(1961, 8, 4)
     tzinfo = tzoffset('-0600', -21600)
     multi_DT_expected = (datetime(1961, 8, 4),
                          datetime(1963, 11, 22, 12, 30, 0, 0,
                                   tzoffset('-0600', -21600)))
     multi_TM_expected = (time(1, 23, 45), time(11, 11, 11))
     TM_expected = time(11, 11, 11, 1)
     ds = read_file(datetime_name)
     # Add date/time data elements
     ds.CalibrationDate = MultiValue(DA, multi_DA_expected)
     ds.DateOfLastCalibration = DA(DA_expected)
     ds.ReferencedDateTime = MultiValue(DT, multi_DT_expected)
     ds.CalibrationTime = MultiValue(TM, multi_TM_expected)
     ds.TimeOfLastCalibration = TM(TM_expected)
     ds.save_as(datetime_out)
     # Now read it back in and check the values are as expected
     ds = read_file(datetime_out)
     self.assertSequenceEqual(multi_DA_expected, ds.CalibrationDate, "Multiple dates not written correctly (VR=DA)")
     self.assertEqual(DA_expected, ds.DateOfLastCalibration, "Date not written correctly (VR=DA)")
     self.assertSequenceEqual(multi_DT_expected, ds.ReferencedDateTime, "Multiple datetimes not written correctly (VR=DT)")
     self.assertSequenceEqual(multi_TM_expected, ds.CalibrationTime, "Multiple times not written correctly (VR=TM)")
     self.assertEqual(TM_expected, ds.TimeOfLastCalibration, "Time not written correctly (VR=DA)")
     if os.path.exists(datetime_out):
         os.remove(datetime_out)  # get rid of the file
Ejemplo n.º 4
0
 def setUp(self):
     self.jpeg_2k = read_file(jpeg2000_name)
     self.jpeg_2k_lossless = read_file(jpeg2000_lossless_name)
     self.mr_small = read_file(mr_name)
     self.emri_jpeg_2k_lossless = read_file(emri_jpeg_2k_lossless)
     self.emri_small = read_file(emri_name)
     self.original_handlers = pydicom.config.image_handlers
     pydicom.config.image_handlers = [gdcm_handler]
Ejemplo n.º 5
0
 def testPlanarConfig(self):
     px_data_ds = read_file(color_px_name)
     pl_data_ds = read_file(color_pl_name)
     assert px_data_ds.PlanarConfiguration != pl_data_ds.PlanarConfiguration
     if have_numpy:
         px_data = px_data_ds.pixel_array
         pl_data = pl_data_ds.pixel_array
         self.assertTrue(numpy.all(px_data == pl_data))
Ejemplo n.º 6
0
    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)
Ejemplo n.º 7
0
 def testwrite_short_uid(self):
     ds = read_file(rtplan_name)
     ds.SOPInstanceUID = "1.2"
     ds.save_as(rtplan_out)
     ds = read_file(rtplan_out)
     ds.save_as(rtplan_out)
     self.assertEqual(ds.SOPInstanceUID, "1.2")
     if os.path.exists(rtplan_out):
         os.remove(rtplan_out)  # get rid of the file
Ejemplo n.º 8
0
 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)
Ejemplo n.º 9
0
 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 = pydicom.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()
Ejemplo n.º 10
0
    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))
Ejemplo n.º 11
0
    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)
Ejemplo n.º 12
0
 def testCTPixelData(self):
     """Check that we can read pixel data. Tests that we get last one in array."""
     ct = read_file(ct_name)
     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)
Ejemplo n.º 13
0
 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))
Ejemplo n.º 14
0
    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 = pydicom.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))
Ejemplo n.º 15
0
 def setUp(self):
     if compat.in_py2:
         self.utf8_filename = os.path.join(tempfile.gettempdir(),
                                           "ДИКОМ.dcm")
         self.unicode_filename = self.utf8_filename.decode("utf8")
         shutil.copyfile(jpeg_ls_lossless_name.decode("utf8"),
                         self.unicode_filename)
     else:
         self.unicode_filename = os.path.join(tempfile.gettempdir(),
                                              "ДИКОМ.dcm")
         shutil.copyfile(jpeg_ls_lossless_name, self.unicode_filename)
     self.jpeg_ls_lossless = read_file(self.unicode_filename)
     self.mr_small = read_file(mr_name)
     self.emri_jpeg_ls_lossless = read_file(emri_jpeg_ls_lossless)
     self.emri_small = read_file(emri_name)
     self.original_handlers = pydicom.config.image_handlers
     pydicom.config.image_handlers = [numpy_handler, gdcm_handler]
Ejemplo n.º 16
0
 def testExplicitVRBigEndianNoMeta(self):
     """Read file without file meta with Big Endian Explicit VR dataset......."""
     # Example file from CMS XiO 5.0 and above
     # Still need to force read data since there is no 'DICM' marker present
     ds = read_file(explicit_vr_be_no_meta, force=True)
     got = ds.InstanceCreationDate
     expected = "20150529"
     self.assertEqual(got, expected, "Sample data element from dataset failed, expected '%s', got '%s'" % (expected, got))
Ejemplo n.º 17
0
 def testExplicitVRBigEndianNoMeta(self):
     """Read file without file meta with Big Endian Explicit VR dataset......."""
     # Example file from CMS XiO 5.0 and above
     # Still need to force read data since there is no 'DICM' marker present
     ds = read_file(explicit_vr_be_no_meta, force=True)
     got = ds.InstanceCreationDate
     expected = "20150529"
     self.assertEqual(got, expected, "Sample data element from dataset failed, expected '%s', got '%s'" % (expected, got))
Ejemplo n.º 18
0
 def dump_file(self, file_path):
     try:
         print('\n' + file_path)
         dataset = filereader.read_file(
             file_path, stop_before_pixels=self.show_image_data, force=True)
         self.print_dataset(dataset)
     except (InvalidDicomError, KeyError):
         print(u'{} is not a valid DICOM file - skipping.'.format(file_path))
Ejemplo n.º 19
0
    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():
            ds.PixelData

        self.assertRaises(IOError, read_value)
Ejemplo n.º 20
0
 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)
Ejemplo n.º 21
0
 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)
     fobj.close()
     # 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
     ds.InstanceNumber
Ejemplo n.º 22
0
    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():
            ds.PixelData

        self.assertRaises(IOError, read_value)
Ejemplo n.º 23
0
 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)
     fobj.close()
     # 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
     ds.InstanceNumber
Ejemplo n.º 24
0
 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))
Ejemplo n.º 25
0
 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))
Ejemplo n.º 26
0
 def testCTPixelData(self):
     """Check that we can read pixel data.
     Tests that we get last one in array.
     """
     ct = read_file(ct_name)
     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)
 def validate_file(self, file_path):
     self.logger.info('\nProcessing DICOM file "%s"', file_path)
     try:
         data_set = filereader.read_file(file_path, stop_before_pixels=True)
     except InvalidDicomError:
         return {file_path: {'fatal': 'Invalid DICOM file'}}
     return {
         file_path: IODValidator(data_set, self._iod_info, self._module_info, self._dict_info,
                                 self.logger.level).validate()
     }
Ejemplo n.º 28
0
 def test_write_no_ts(self):
     """Test reading a file with no ts and writing it out identically."""
     written_file = TemporaryFile('w+b')
     ds = read_file(no_ts)
     ds.save_as(written_file, write_like_original=True)
     written_file.seek(0)
     with open(no_ts, 'rb') as ref_file:
         written_bytes = written_file.read()
         read_bytes = ref_file.read()
         self.compare_bytes(read_bytes, written_bytes)
Ejemplo n.º 29
0
 def testEmptyNumbersTag(self):
     """Tests that an empty tag with a number VR (FL, UL, SL, US, SS, FL, FD, OF) reads as an empty string"""
     empty_number_tags_ds = read_file(empty_number_tags_name)
     self.assertEqual(empty_number_tags_ds.ExaminedBodyThickness, "")
     self.assertEqual(empty_number_tags_ds.SimpleFrameList, "")
     self.assertEqual(empty_number_tags_ds.ReferencePixelX0, "")
     self.assertEqual(empty_number_tags_ds.PhysicalUnitsXDirection, "")
     self.assertEqual(empty_number_tags_ds.TagAngleSecondAxis, "")
     self.assertEqual(empty_number_tags_ds.TagSpacingSecondDimension, "")
     self.assertEqual(empty_number_tags_ds.VectorGridData, "")
Ejemplo n.º 30
0
    def testNoTransferSyntaxInMeta(self):
        """Read file with file_meta, but has no TransferSyntaxUID in it............"""
        # From issue 258: if file has file_meta but no TransferSyntaxUID in it,
        #   should assume default transfer syntax
        ds = read_file(meta_missing_tsyntax_name)  # is dicom default transfer syntax

        # Repeat one test from nested private sequence test to maker sure
        #    file was read correctly
        pixel_data_tag = TupleTag((0x7FE0, 0x10))
        self.assertTrue(pixel_data_tag in ds, "Failed to properly read a file with no Transfer Syntax in file_meta")
Ejemplo n.º 31
0
 def testSpecificTags(self):
     """Returns only tags specified by user."""
     ctspecific = read_file(ct_name, specific_tags=[
         Tag(0x0010, 0x0010), 'PatientID', 'ImageType', 'ViewName'])
     ctspecific_tags = sorted(ctspecific.keys())
     expected = [
         # ViewName does not exist in the data set
         Tag(0x0008, 0x0008), Tag(0x0010, 0x0010), Tag(0x0010, 0x0020)
     ]
     self.assertEqual(expected, ctspecific_tags)
Ejemplo n.º 32
0
 def testEmptyNumbersTag(self):
     """Tests that an empty tag with a number VR (FL, UL, SL, US, SS, FL, FD, OF) reads as an empty string"""
     empty_number_tags_ds = read_file(empty_number_tags_name)
     self.assertEqual(empty_number_tags_ds.ExaminedBodyThickness, '')
     self.assertEqual(empty_number_tags_ds.SimpleFrameList, '')
     self.assertEqual(empty_number_tags_ds.ReferencePixelX0, '')
     self.assertEqual(empty_number_tags_ds.PhysicalUnitsXDirection, '')
     self.assertEqual(empty_number_tags_ds.TagAngleSecondAxis, '')
     self.assertEqual(empty_number_tags_ds.TagSpacingSecondDimension, '')
     self.assertEqual(empty_number_tags_ds.VectorGridData, '')
Ejemplo n.º 33
0
 def testReadFileWithMissingPixelDataArray(self):
     mr = read_file(truncated_mr_name)
     mr.decode()
     msg = (r"(Amount of pixel data.*"
            "does not match the expected data|"
            "Unexpected end of file. Read.*bytes of.*expected|"
            "'str' object has no attribute 'reshape'|"
            "'bytes' object has no attribute 'reshape')")
     with self.assertRaisesRegexp(AttributeError, msg):
         mr.pixel_array
Ejemplo n.º 34
0
 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))
Ejemplo n.º 35
0
    def test_read_UR_explicit_little(self):
        """Check creation of DataElement from byte data works correctly."""
        ds = read_file(self.fp_ex, force=True)
        ref_elem = ds.get(0x00080120)  # URNCodeValue
        elem = DataElement(0x00080120, 'UR', 'http://test.com')
        self.assertEqual(ref_elem, elem)

        # Test trailing spaces ignored
        ref_elem = ds.get(0x00081190)  # RetrieveURL
        elem = DataElement(0x00081190, 'UR', 'ftp://test.com')
        self.assertEqual(ref_elem, elem)
Ejemplo n.º 36
0
 def test_meta_no_dataset(self):
     """Test reading only meta elements"""
     bytestream = b'\x02\x00\x00\x00\x55\x4C\x04\x00\x0A\x00\x00\x00' \
                  b'\x02\x00\x02\x00\x55\x49\x16\x00\x31\x2e\x32\x2e\x38\x34\x30\x2e\x31' \
                  b'\x30\x30\x30\x38\x2e\x35\x2e\x31\x2e\x31\x2e\x39\x00\x02\x00\x10\x00' \
                  b'\x55\x49\x12\x00\x31\x2e\x32\x2e\x38\x34\x30\x2e\x31\x30\x30\x30\x38' \
                  b'\x2e\x31\x2e\x32\x00'
     fp = BytesIO(bytestream)
     ds = read_file(fp, force=True)
     self.assertTrue('TransferSyntaxUID' in ds.file_meta)
     self.assertEqual(ds[:], Dataset())
Ejemplo n.º 37
0
    def __initialized(self):

        try:
            header =  read_file(self.__filename, defer_size=None, stop_before_pixels=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.__echoTime = header.EchoTime
            self.__isDicom = True

        except AttributeError as a:
            if "EchoTime" in a.message:
                try:
                    self.__echoTime = header[Tag((0x2001, 0x1025))].value
                    self.__isDicom = True
                except KeyError as k:
                    self.__isDicom = False
            else:
                 self.__isDicom = False

        if self.isSiemens():
            #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 dicom, 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
Ejemplo n.º 38
0
    def testNoTransferSyntaxInMeta(self):
        """Read file with file_meta, but has no TransferSyntaxUID in it............"""
        # From issue 258: if file has file_meta but no TransferSyntaxUID in it,
        #   should assume default transfer syntax
        ds = read_file(meta_missing_tsyntax_name)  # is dicom default transfer syntax

        # Repeat one test from nested private sequence test to maker sure
        #    file was read correctly
        pixel_data_tag = TupleTag((0x7fe0, 0x10))
        self.assertTrue(pixel_data_tag in ds,
                        "Failed to properly read a file with no Transfer Syntax in file_meta")
Ejemplo n.º 39
0
 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.assertTrue(ds.ImageType[1] == CS_expected,
                     "Item in a list not written correctly to file (VR=CS)")
     self.assertTrue(ds[0x00431012].value[0] == SS_expected,
                     "Item in a list not written correctly to file (VR=SS)")
     self.assertTrue(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)
Ejemplo n.º 40
0
 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.assertTrue(ds.ImageType[1] == CS_expected,
                     "Item in a list not written correctly to file (VR=CS)")
     self.assertTrue(ds[0x00431012].value[0] == SS_expected,
                     "Item in a list not written correctly to file (VR=SS)")
     self.assertTrue(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)
Ejemplo n.º 41
0
 def testReadFileWithMissingPixelData(self):
     mr = read_file(truncated_mr_name)
     mr.decode()
     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
     DS = pydicom.valuerep.DS
     expected = [DS('0.3125'), DS('0.3125')]
     self.assertTrue(got == expected, "Wrong pixel spacing")
Ejemplo n.º 42
0
 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'
     mr.decode()
     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
     DS = pydicom.valuerep.DS
     expected = [DS('0.3125'), DS('0.3125')]
     self.assertTrue(got == expected, "Wrong pixel spacing")
Ejemplo n.º 43
0
 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'
     mr.decode()
     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
     DS = pydicom.valuerep.DS
     expected = [DS('0.3125'), DS('0.3125')]
     self.assertTrue(got == expected, "Wrong pixel spacing")
Ejemplo n.º 44
0
    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")
Ejemplo n.º 45
0
    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")
Ejemplo n.º 46
0
 def testReadFileWithMissingPixelData(self):
     mr = read_file(truncated_mr_name)
     mr.decode()
     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
     DS = pydicom.valuerep.DS
     expected = [DS('0.3125'), DS('0.3125')]
     self.assertTrue(got == expected, "Wrong pixel spacing")
     with self.assertRaisesRegexp(AttributeError, "Amount of pixel data.*does not match the expected data"):
         mr.pixel_array
Ejemplo n.º 47
0
 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 = pydicom.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()
Ejemplo n.º 48
0
    def test_long_specific_char_set(self):
        """Test that specific character set is read even if it is longer than defer_size"""
        ds = Dataset()

        long_specific_char_set_value = ['ISO 2022IR 100'] * 9
        ds.add(DataElement(0x00080005, 'CS', long_specific_char_set_value))

        fp = BytesIO()
        file_ds = FileDataset(fp, ds)
        file_ds.save_as(fp)

        ds = read_file(fp, defer_size=65, force=True)
        self.assertEqual(ds[0x00080005].value, long_specific_char_set_value)
Ejemplo n.º 49
0
    def test_read_UR(self):
        """Check creation of DataElement from byte data works correctly."""
        ds = read_file(self.fp, force=True)
        ref_elem = ds.get(0x00080120)  # URNCodeValue
        ref_elem.file_tell = None  # Workaround for Issue #294
        elem = DataElement(0x00080120, 'UR', 'http://test.com')
        self.assertEqual(ref_elem, elem)

        # Test trailing spaces ignored
        ref_elem = ds.get(0x00081190)  # RetrieveURL
        ref_elem.file_tell = None  # Workaround for Issue #294
        elem = DataElement(0x00081190, 'UR', 'ftp://test.com')
        self.assertEqual(ref_elem, elem)
Ejemplo n.º 50
0
 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 = pydicom.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()
Ejemplo n.º 51
0
 def test_commandset_no_dataset(self):
     """Test reading only command set elements"""
     bytestream = (b'\x00\x00\x00\x00\x04\x00\x00\x00\x38'
                   b'\x00\x00\x00\x00\x00\x02\x00\x12\x00\x00'
                   b'\x00\x31\x2e\x32\x2e\x38\x34\x30\x2e\x31'
                   b'\x30\x30\x30\x38\x2e\x31\x2e\x31\x00\x00'
                   b'\x00\x00\x01\x02\x00\x00\x00\x30\x00\x00'
                   b'\x00\x10\x01\x02\x00\x00\x00\x07\x00\x00'
                   b'\x00\x00\x08\x02\x00\x00\x00\x01\x01')
     fp = BytesIO(bytestream)
     ds = read_file(fp, force=True)
     self.assertTrue('MessageID' in ds)
     self.assertTrue(ds.preamble is None)
     self.assertEqual(ds.file_meta, Dataset())
Ejemplo n.º 52
0
    def compare(self, in_filename, out_filename, decode=False):
        """Read file1, write file2, then compare.
        Return value as for files_identical.
        """
        dataset = read_file(in_filename)
        if decode:
            dataset.decode()

        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
Ejemplo n.º 53
0
    def test_no_preamble_file_meta(self):
        """Test correct read of group 2 elements with no preamble."""
        bytestream = b'\x02\x00\x02\x00\x55\x49\x16\x00\x31\x2e\x32\x2e\x38\x34\x30\x2e\x31' \
                     b'\x30\x30\x30\x38\x2e\x35\x2e\x31\x2e\x31\x2e\x39\x00\x02\x00\x10\x00' \
                     b'\x55\x49\x12\x00\x31\x2e\x32\x2e\x38\x34\x30\x2e\x31\x30\x30\x30\x38' \
                     b'\x2e\x31\x2e\x32\x00\x20\x20\x10\x00\x02\x00\x00\x00\x01\x00\x20\x20' \
                     b'\x20\x00\x06\x00\x00\x00\x4e\x4f\x52\x4d\x41\x4c'

        fp = BytesIO(bytestream)
        ds = read_file(fp, force=True)
        self.assertTrue('MediaStorageSOPClassUID' in ds.file_meta)
        self.assertEqual(ds.file_meta.TransferSyntaxUID, ImplicitVRLittleEndian)
        self.assertEqual(ds.Polarity, 'NORMAL')
        self.assertEqual(ds.ImageBoxPosition, 1)
Ejemplo n.º 54
0
    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)
            with open(self.testfile_name, "r+") as f:
                f.write('\0')  # "touch" the file
            warning_start = "Deferred read warning -- file modification time "

            def read_value():
                ds.PixelData

            assertWarns(self, warning_start, read_value)
Ejemplo n.º 55
0
    def compare(self, in_filename, out_filename, decode=False):
        """Read file1, write file2, then compare.
        Return value as for files_identical.
        """
        dataset = read_file(in_filename)
        if decode:
            dataset.decode()

        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
Ejemplo n.º 56
0
    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)
            with open(self.testfile_name, "r+") as f:
                f.write('\0')  # "touch" the file
            warning_start = "Deferred read warning -- file modification time "

            def read_value():
                ds.PixelData

            assertWarns(self, warning_start, read_value)
Ejemplo n.º 57
0
 def test_read_file_does_not_raise(self):
     """Test that reading from DicomBytesIO does not raise on EOF.
     Regression test for #358."""
     ds = read_file(mr_name)
     fp = DicomBytesIO()
     ds.save_as(fp)
     fp.seek(0)
     de_gen = data_element_generator(fp, False, True)
     try:
         while True:
             next(de_gen)
     except StopIteration:
         pass
     except EOFError:
         self.fail('Unexpected EOFError raised')
Ejemplo n.º 58
0
    def test_correct_ambiguous_vr(self):
        """Test correcting ambiguous VR elements read from file"""
        ds = Dataset()
        ds.PixelRepresentation = 0
        ds.add(DataElement(0x00280108, 'US', 10))
        ds.add(DataElement(0x00280109, 'US', 500))

        fp = BytesIO()
        file_ds = FileDataset(fp, ds)
        file_ds.is_implicit_VR = True
        file_ds.is_little_endian = True
        file_ds.save_as(fp)

        ds = read_file(fp, force=True)
        self.assertEqual(ds[0x00280108].VR, 'US')
        self.assertEqual(ds.SmallestPixelValueInSeries, 10)
Ejemplo n.º 59
0
    def test_preamble_meta_no_dataset(self):
        """Test reading only preamble and meta elements"""
        preamble = b'\x00' * 128
        prefix = b'DICM'
        meta = b'\x02\x00\x00\x00\x55\x4C\x04\x00\x0A\x00\x00\x00' \
               b'\x02\x00\x02\x00\x55\x49\x16\x00\x31\x2e\x32\x2e\x38\x34\x30\x2e\x31' \
               b'\x30\x30\x30\x38\x2e\x35\x2e\x31\x2e\x31\x2e\x39\x00\x02\x00\x10\x00' \
               b'\x55\x49\x12\x00\x31\x2e\x32\x2e\x38\x34\x30\x2e\x31\x30\x30\x30\x38' \
               b'\x2e\x31\x2e\x32\x00'

        bytestream = preamble + prefix + meta
        fp = BytesIO(bytestream)
        ds = read_file(fp, force=True)
        self.assertEqual(ds.preamble, b'\x00' * 128)
        self.assertTrue('TransferSyntaxUID' in ds.file_meta)
        self.assertEqual(ds[:], Dataset())
Ejemplo n.º 60
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"]
        for name in expect_in_dir:
            self.assertTrue(name in got_dir, "Expected 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"]
        for name in expect_in_dir:
            self.assertTrue(name in got_dir, "Expected name '%s' in dir()" % name)