Exemplo n.º 1
0
 def setup(self):
     self.enc = RLELosslessEncoder
     self.ds = get_testdata_file("CT_small.dcm", read=True)
     self.ds_enc = get_testdata_file("MR_small_RLE.dcm", read=True)
     self.ds_enc_mf = get_testdata_file("emri_small_RLE.dcm", read=True)
     self.bytes = self.ds.PixelData
     self.arr = self.ds.pixel_array
     self.kwargs = self.enc.kwargs_from_ds(self.ds)
    def setup(self):
        """Setup the benchmark."""
        self.no_runs = 1000

        ds = dcmread(get_testdata_file('SC_rgb_gdcm2k_uncompressed.dcm'))
        self.rgb = ds.pixel_array
        ds = dcmread(get_testdata_file('SC_ybr_full_uncompressed.dcm'))
        self.ybr_full = ds.pixel_array
Exemplo n.º 3
0
    def setup(self):
        """Setup the benchmark."""
        self.no_runs = 1000

        ds = dcmread(get_testdata_file('SC_rgb_gdcm2k_uncompressed.dcm'))
        self.rgb = ds.pixel_array
        ds = dcmread(get_testdata_file('SC_ybr_full_uncompressed.dcm'))
        self.ybr_full = ds.pixel_array

        self.arr_large = np.ones((10, 1024, 1024, 3), dtype=np.uint8)
        self.arr_32_3_2f = dcmread(EXPL_32_3_2F).pixel_array
Exemplo n.º 4
0
    def test_from_dicom(self):
        mr_dcm = get_testdata_file("MR_small.dcm")
        fs = pydicom.read_file(mr_dcm)
        arr = fs.pixel_array

        scan = MockScanIOMixin.from_dicom(mr_dcm, foo="foofoo", bar="barbar")
        assert len(scan.volumes) == 1
        assert np.all(scan.volumes[0] == arr[..., np.newaxis])
        assert scan.foo == "foofoo"
        assert scan._bar == "barbar"
        assert scan._from_file_args == {
            "dir_or_files": mr_dcm,
            "ignore_ext": False,
            "group_by": None,
            "_type": "dicom",
        }

        scan = MockScanIOMixin.from_dicom([mr_dcm], foo="foofoo", bar="barbar")
        assert len(scan.volumes) == 1
        assert np.all(scan.volumes[0] == arr[..., np.newaxis])
        assert scan.foo == "foofoo"
        assert scan._bar == "barbar"
        assert scan._from_file_args == {
            "dir_or_files": [mr_dcm],
            "ignore_ext": False,
            "group_by": None,
            "_type": "dicom",
        }
Exemplo n.º 5
0
 def test_code_file(self, capsys):
     """Test utils.codify.code_file"""
     filename = get_testdata_file("rtplan.dcm")
     args = ["--save-as", r"c:\temp\testout.dcm", filename]
     codify_main(100, args)
     out, err = capsys.readouterr()
     assert r"c:\temp\testout.dcm" in out
Exemplo n.º 6
0
 def test_UN_sequence(self):
     p = get_testdata_file("UN_sequence.dcm")
     msg = "This reader does not handle undefined length except for SQ"
     with dicomfile(p) as ds:
         with pytest.raises(NotImplementedError, match=msg):
             for elem in ds:
                 pass
Exemplo n.º 7
0
    def test_hexdump(self):
        """Test utils.dump.hexdump"""
        # Default
        p = get_testdata_file("CT_small.dcm")
        with open(p, 'rb') as f:
            s = hexdump(f)

        assert (
            "0000  49 49 2A 00 54 18 08 00 00 00 00 00 00 00 00 00  "
            "II*.T..........."
        ) in s
        assert (
            "0170  41 4C 5C 50 52 49 4D 41 52 59 5C 41 58 49 41 4C  "
            "AL.PRIMARY.AXIAL"
        ) in s
        assert (
            "9920  08 00 00 00 00 00                                ......"
        ) in s

        # `stop_address` parameter
        with open(p, 'rb') as f:
            s = hexdump(f, stop_address=1000)

        assert (
            "000  49 49 2A 00 54 18 08 00 00 00 00 00 00 00 00 00  "
            "II*.T..........."
        ) in s
        assert (
            "170  41 4C 5C 50 52 49 4D 41 52 59 5C 41 58 49 41 4C  "
            "AL.PRIMARY.AXIAL"
        ) in s
        assert (
            "9920  08 00 00 00 00 00                                ......"
        ) not in s

        # `show_address` parameter
        with open(p, 'rb') as f:
            s = hexdump(f, show_address=False, stop_address=1000)

        assert (
            "49 49 2A 00 54 18 08 00 00 00 00 00 00 00 00 00  "
            "II*.T..........."
        ) in s
        assert (
            "000  49 49 2A 00 54 18 08 00 00 00 00 00 00 00 00 00  "
            "II*.T..........."
        ) not in s

        # `start_address` parameter
        with open(p, 'rb') as f:
            s = hexdump(f, start_address=500, stop_address=1000)

        assert (
            "000  49 49 2A 00 54 18 08 00 00 00 00 00 00 00 00 00  "
            "II*.T..........."
        ) not in s
        assert (
            "1F4  2E 31 2E 31 2E 31 2E 31 2E 32 30 30 34 30 31 31  "
            ".1.1.1.1.2004011"
        ) in s
Exemplo n.º 8
0
 def test_invalid_sop_file_meta(self):
     """Test exception raised if SOP Class is not Media Storage Directory"""
     ds = dcmread(get_testdata_file('CT_small.dcm'))
     with pytest.raises(InvalidDicomError,
                        match=r"SOP Class is not Media Storage "
                        r"Directory \(DICOMDIR\)"):
         DicomDir("some_name", ds, b'\x00' * 128, ds.file_meta, True, True)
Exemplo n.º 9
0
 def test_invalid_sop_no_file_meta(self):
     """Test exception raised if invalid sop class but no file_meta"""
     ds = dcmread(get_testdata_file('CT_small.dcm'))
     with pytest.raises(AttributeError,
                        match="'DicomDir' object has no attribute "
                        "'DirectoryRecordSequence'"):
         DicomDir("some_name", ds, b'\x00' * 128, None, True, True)
Exemplo n.º 10
0
 def test_invalid_character_set_enforce_valid(self, enforce_valid_values):
     """charset: raise on invalid encoding"""
     ds = dcmread(get_testdata_file("CT_small.dcm"))
     ds.read_encoding = None
     ds.SpecificCharacterSet = "UNSUPPORTED"
     with pytest.raises(LookupError,
                        match="Unknown encoding 'UNSUPPORTED'"):
         ds.decode()
Exemplo n.º 11
0
 def test_no_meta(self):
     p = get_testdata_file("no_meta.dcm")
     msg = "No transfer syntax in file meta info"
     with dicomfile(p) as ds:
         assert ds.preamble is None
         with pytest.raises(NotImplementedError, match=msg):
             for elem in ds:
                 pass
Exemplo n.º 12
0
 def test_read_pydicom_data_file_is_FileDataset(self):
     """
         - Read dicom file from pydicom test data files
         - Check is a FileDataSet
     """
     mr_name = get_testdata_file("MR_small.dcm")
     ds = dcmread(mr_name)
     self.assertEqual(FileDataset, type(ds))
Exemplo n.º 13
0
 def test_pydicom_external(self):
     """Test that pydicom uses external data sources first."""
     fname = "693_UNCI.dcm"
     fpath = get_testdata_file(fname)
     if HAVE_EXT_SOURCES:
         assert os.fspath(self.data_path / fname) == fpath
     else:
         assert ".pydicom/data" in fpath
Exemplo n.º 14
0
    def test_datadump(self):
        """Test utils.dump.datadump"""
        p = get_testdata_file("CT_small.dcm")
        with open(p, 'rb') as f:
            s = datadump(f.read(), 500, 1000)

        assert ("1F4  2E 31 2E 31 2E 31 2E 31 2E 32 30 30 34 30 31 31  "
                ".1.1.1.1.2004011") in s
Exemplo n.º 15
0
    def test_uid_not_supported(self):
        """Test the UID not having any encoders."""
        ds = get_testdata_file("CT_small.dcm", read=True)

        msg = (r"No pixel data encoders have been implemented for "
               r"'JPEG 2000 Part 2 Multi-component Image Compression'")
        with pytest.raises(NotImplementedError, match=msg):
            ds.compress(JPEG2000MC, encoding_plugin='pydicom')
Exemplo n.º 16
0
 def test_invalid_sop_no_file_meta(self, allow_reading_invalid_values):
     """Test exception raised if invalid sop class but no file_meta"""
     ds = dcmread(get_testdata_file('CT_small.dcm'))
     with pytest.raises(AttributeError,
                        match="'DicomDir' object has no attribute "
                        "'DirectoryRecordSequence'"):
         with pytest.warns(UserWarning, match=r"Invalid transfer syntax"):
             DicomDir("some_name", ds, b'\x00' * 128, None, True, True)
Exemplo n.º 17
0
 def test_json_pn_from_file(self):
     with open(get_testdata_file("test_PN.json")) as s:
         ds = Dataset.from_json(s.read())
     assert isinstance(ds[0x00080090].value, PersonName)
     assert isinstance(ds[0x00100010].value, PersonName)
     inner_seq = ds[0x04000561].value[0][0x04000550]
     dataelem = inner_seq[0][0x00100010]
     assert isinstance(dataelem.value, PersonName)
Exemplo n.º 18
0
    def test_save_load(self):
        mr_dcm = get_testdata_file("MR_small.dcm")
        scan = MockScanIOMixin.from_dicom(mr_dcm)
        scan.foo = "foofoo"
        scan._bar = "barbar"

        vars = scan.__serializable_variables__()
        serializable = ("foo", "_bar", "volumes", "_from_file_args")
        not_serializable = ("_temp_path", "__some_attr__", "__pydicom_header__", "some_property")
        assert all(x in vars for x in serializable)
        assert all(x not in vars for x in not_serializable)

        save_dir = os.path.join(self.data_dirpath, "test_save_load")
        save_path = scan.save(save_dir, save_custom=True)
        assert os.path.isfile(save_path)

        scan_loaded = MockScanIOMixin.load(save_path)
        assert scan_loaded.volumes[0].is_identical(scan.volumes[0])
        assert scan_loaded.foo == "foofoo"
        assert scan._bar == "barbar"

        scan_loaded = MockScanIOMixin.load(save_dir)
        assert scan_loaded.volumes[0].is_identical(scan.volumes[0])
        assert scan_loaded.foo == "foofoo"
        assert scan._bar == "barbar"

        with self.assertRaises(FileNotFoundError):
            _ = MockScanIOMixin.load(os.path.join(save_dir, "some-path.pik"))

        new_dict = dict(scan.__dict__)
        new_dict.pop("volumes")
        with self.assertWarns(UserWarning):
            scan_loaded = MockScanIOMixin.load(new_dict)
        assert scan_loaded.volumes[0].is_identical(scan.volumes[0])
        assert scan_loaded.foo == "foofoo"
        assert scan._bar == "barbar"

        # Backwards compatibility with how DOSMA wrote files versions<0.0.12
        new_dict = dict(scan.__dict__)
        new_dict.pop("volumes")
        new_dict.pop("_from_file_args")
        new_dict.update({"dicom_path": mr_dcm, "ignore_ext": False, "series_number": 7})
        with self.assertWarns(UserWarning):
            scan_loaded = MockScanIOMixin.load(new_dict)
        assert scan_loaded.volumes[0].is_identical(scan.volumes[0])
        assert scan_loaded.foo == "foofoo"
        assert scan._bar == "barbar"

        new_dict = dict(scan.__dict__)
        new_dict.pop("volumes")
        new_dict.pop("_from_file_args")
        with self.assertRaises(ValueError):
            _ = MockScanIOMixin.load(new_dict)

        save_dir = os.path.join(self.data_dirpath, "test_save_data")
        with self.assertWarns(DeprecationWarning):
            scan.save_data(save_dir)
 def test_decompress_using_pillow(self):
     """Test decompressing JPEG2K with pillow handler succeeds."""
     ds = dcmread(J2KR_16_14_1_1_1F_M2)
     ds.BitsStored = 14
     ds.decompress(handler_name='pillow')
     arr = ds.pixel_array
     ds = dcmread(get_testdata_file("693_UNCR.dcm"))
     ref = ds.pixel_array
     assert np.array_equal(arr, ref)
Exemplo n.º 20
0
 def test_nested_sequences(self):
     test1_json = get_testdata_file("test1.json")
     with open(test1_json) as f:
         with pytest.warns(UserWarning,
                           match='no bulk data URI handler provided '):
             ds = Dataset.from_json(f.read())
         del ds.PixelData
     ds2 = Dataset.from_json(ds.to_json())
     assert ds == ds2
Exemplo n.º 21
0
    def test_json_from_dicom_file(self, no_numpy_use):
        ds1 = Dataset(dcmread(get_testdata_file("CT_small.dcm")))
        ds_json = ds1.to_json()
        ds2 = Dataset.from_json(ds_json)
        assert ds1 == ds2

        ds_json = ds1.to_json_dict()
        ds2 = Dataset.from_json(ds_json)
        assert ds1 == ds2
Exemplo n.º 22
0
    def test_decompress_using_pylibjpeg(self):
        """Test decompressing RLE with pylibjpeg handler succeeds."""
        ds = dcmread(RLE_8_3_1F)
        ds.decompress(handler_name='pylibjpeg')
        arr = ds.pixel_array

        ds = dcmread(get_testdata_file("SC_rgb.dcm"))
        ref = ds.pixel_array
        assert np.array_equal(arr, ref)
Exemplo n.º 23
0
 def test_explicit_big(self):
     p = get_testdata_file("MR_small_bigendian.dcm")
     ds = dcmread(p)
     assert ds.file_meta.TransferSyntaxUID == ExplicitVRBigEndian
     with dicomfile(p) as ds:
         assert ds.preamble is not None
         for elem in ds:
             if elem[0] == (0x7fe0, 0x0010):
                 assert elem[2] == 8192
Exemplo n.º 24
0
 def test_explicit_little(self):
     p = get_testdata_file("CT_small.dcm")
     ds = dcmread(p)
     assert ds.file_meta.TransferSyntaxUID == ExplicitVRLittleEndian
     with dicomfile(p) as ds:
         assert ds.preamble is not None
         for elem in ds:
             if elem[0] == (0x7fe0, 0x0010):
                 assert elem[2] == 32768
Exemplo n.º 25
0
 def test_round_trip(self):
     """Test an encoding round-trip"""
     ds = get_testdata_file("MR_small_RLE.dcm", read=True)
     original = ds.PixelData
     arr = ds.pixel_array
     del ds.PixelData
     ds.compress(RLELossless, arr, encoding_plugin="pydicom")
     assert id(ds.pixel_array) != id(arr)
     assert np.array_equal(arr, ds.pixel_array)
Exemplo n.º 26
0
 def test_planar_configuration(self):
     """Test Planar Configuration added if Samples per Pixel > 1"""
     ds = get_testdata_file("SC_rgb_small_odd.dcm", read=True)
     del ds.PlanarConfiguration
     assert ds.SamplesPerPixel == 3
     assert 'PlanarConfiguration' not in ds
     ds.compress(RLELossless, encoding_plugin='pydicom')
     assert ds.file_meta.TransferSyntaxUID == RLELossless
     assert ds.PlanarConfiguration == 1
Exemplo n.º 27
0
 def test_compress_inplace(self):
     """Test encode with a dataset."""
     ds = get_testdata_file("CT_small.dcm", read=True)
     ds.compress(RLELossless, encoding_plugin='pydicom')
     assert ds.SamplesPerPixel == 1
     assert ds.file_meta.TransferSyntaxUID == RLELossless
     assert len(ds.PixelData) == 21370
     assert 'PlanarConfiguration' not in ds
     assert ds['PixelData'].is_undefined_length
Exemplo n.º 28
0
    def test_decompress_using_pylibjpeg(self):
        """Test decompressing JPEG2K with pylibjpeg handler succeeds."""
        ds = dcmread(J2KR_16_12_1_0_1F_M2)
        ds.decompress(handler_name='pylibjpeg')
        arr = ds.pixel_array

        ds = dcmread(get_testdata_file("MR2_J2KR.dcm"))
        ref = ds.pixel_array
        assert np.array_equal(arr, ref)
Exemplo n.º 29
0
    def test_filedump(self):
        """Test utils.dump.filedump"""
        p = get_testdata_file("CT_small.dcm")
        s = filedump(p, start_address=500, stop_address=1000)

        assert ("000  49 49 2A 00 54 18 08 00 00 00 00 00 00 00 00 00  "
                "II*.T...........") not in s
        assert ("1F4  2E 31 2E 31 2E 31 2E 31 2E 32 30 30 34 30 31 31  "
                ".1.1.1.1.2004011") in s
Exemplo n.º 30
0
 def test_no_tsyntax(self):
     p = get_testdata_file("meta_missing_tsyntax.dcm")
     ds = dcmread(p)
     assert "TransferSyntaxUID" not in ds.file_meta
     msg = "No transfer syntax in file meta info"
     with dicomfile(p) as ds:
         assert ds.preamble is not None
         with pytest.raises(NotImplementedError, match=msg):
             for elem in ds:
                 pass