示例#1
0
 def test_invalid_sop_file_meta(self):
     """Test exception raised if SOP Class is not Media Storage Directory"""
     ds = read_file(get_testdata_files('CT_small.dcm')[0])
     with pytest.raises(InvalidDicomError,
                        match="SOP Class is not Media Storage "
                              "Directory \(DICOMDIR\)"):
         DicomDir("some_name", ds, b'\x00' * 128, ds.file_meta, True, True)
 def testJPEGlossless_odd_data_size(self):
     """Test decoding JPEG with pillow handler succeeds."""
     test_file = get_testdata_files('SC_rgb_small_odd_jpeg.dcm')[0]
     ds = dcmread(test_file)
     pixel_data = ds.pixel_array
     assert pixel_data.nbytes == 27
     assert pixel_data.shape == (3, 3, 3)
示例#3
0
 def test_invalid_sop_no_file_meta(self):
     """Test exception raised if invalid sop class but no file_meta"""
     ds = read_file(get_testdata_files('CT_small.dcm')[0])
     with pytest.raises(AttributeError,
                        match="'DicomDir' object has no attribute "
                              "'DirectoryRecordSequence'"):
         DicomDir("some_name", ds, b'\x00' * 128, None, True, True)
示例#4
0
    def test_get_dataset(self):
        """Test the different functions to get lists of data files."""

        # Test base locations
        charbase = os.path.join(DATA_ROOT, 'charset_files')
        self.assertTrue(os.path.exists(charbase))

        testbase = os.path.join(DATA_ROOT, 'test_files')
        self.assertTrue(os.path.exists(testbase))

        # Test file get
        chardata = get_charset_files()
        self.assertTrue(len(chardata) > 15)

        # Test that top level file is included
        bases = [basename(x) for x in chardata]

        # Test that subdirectory files included
        testdata = get_testdata_files()
        bases = [basename(x) for x in testdata]
        self.assertTrue('2693' in bases)
        self.assertTrue(len(testdata) > 70)

        # The files should be from their respective bases
        [self.assertTrue(testbase in x) for x in testdata]
        [self.assertTrue(charbase in x) for x in chardata]
示例#5
0
 def test_code_file(self, capsys):
     """Test utils.codify.code_file"""
     filename = get_testdata_files("rtplan.dcm")[0]
     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
示例#6
0
 def test_invalid_character_set_enforce_valid(self):
     """charset: raise on invalid encoding"""
     config.enforce_valid_values = True
     ds = dcmread(get_testdata_files("CT_small.dcm")[0])
     ds.read_encoding = None
     ds.SpecificCharacterSet = 'Unsupported'
     with pytest.raises(LookupError, match='unknown encoding: Unsupported'):
         ds.decode()
示例#7
0
 def test_trait_names(self):
     """Test Dataset.trait_names contains element keywords"""
     test_file = get_testdata_files('CT_small.dcm')[0]
     ds = dcmread(test_file, force=True)
     names = ds.trait_names()
     assert 'PatientName' in names
     assert 'save_as' in names
     assert 'PixelData' in names
示例#8
0
    def test_get_dataset_pattern(self):
        """Test that pattern is working properly."""

        pattern = 'CT_small'
        filename = get_testdata_files(pattern)
        self.assertTrue(filename[0].endswith('CT_small.dcm'))

        pattern = 'chrX1'
        filename = get_charset_files(pattern)
        self.assertTrue(filename[0].endswith('chrX1.dcm'))
示例#9
0
 def test_invalid_character_set(self):
     """charset: replace invalid encoding with default encoding"""
     ds = dcmread(get_testdata_files("CT_small.dcm")[0])
     ds.read_encoding = None
     ds.SpecificCharacterSet = 'Unsupported'
     with pytest.warns(UserWarning,
                       match=u"Unknown encoding 'Unsupported' "
                             u"- using default encoding instead"):
         ds.decode()
         assert u'CompressedSamples^CT1' == ds.PatientName
示例#10
0
    def test_set_convert_private_elem_from_raw(self):
        """Test Dataset.__setitem__ with a raw private element"""
        test_file = get_testdata_files('CT_small.dcm')[0]
        ds = dcmread(test_file, force=True)
        # 'tag VR length value value_tell is_implicit_VR is_little_endian'
        elem = RawDataElement((0x0043, 0x1029), 'OB', 2, b'\x00\x01', 0,
                              True, True)
        ds.__setitem__((0x0043, 0x1029), elem)

        assert ds[(0x0043, 0x1029)].value == b'\x00\x01'
        assert type(ds[(0x0043, 0x1029)]) == DataElement
示例#11
0
    def test_get_item(self):
        """Test Dataset.get_item"""
        ds = Dataset()
        ds.CommandGroupLength = 120  # 0000,0000
        ds.SOPInstanceUID = '1.2.3.4'  # 0008,0018

        # Test non-deferred read
        assert ds.get_item(0x00000000) == ds[0x00000000]
        assert ds.get_item(0x00000000).value == 120
        assert ds.get_item(0x00080018) == ds[0x00080018]
        assert ds.get_item(0x00080018).value == '1.2.3.4'

        # Test deferred read
        test_file = get_testdata_files('MR_small.dcm')[0]
        ds = dcmread(test_file, force=True, defer_size='0.8 kB')
        ds_ref = dcmread(test_file, force=True)
        # get_item will follow the deferred read branch
        assert ds.get_item((0x7fe00010)).value == ds_ref.PixelData
示例#12
0
This examples illustrates how to find the differences between two DICOM files.

"""

# authors : Guillaume Lemaitre <*****@*****.**>
# license : MIT

import difflib

import pydicom
from pydicom.data import get_testdata_files

print(__doc__)

filename_mr = get_testdata_files('MR_small.dcm')[0]
filename_ct = get_testdata_files('CT_small.dcm')[0]

datasets = tuple([
    pydicom.read_file(filename, force=True)
    for filename in (filename_mr, filename_ct)
])

# difflib compare functions require a list of lines, each terminated with
# newline character massage the string representation of each dicom dataset
# into this form:
rep = []
for dataset in datasets:
    lines = str(dataset).split("\n")
    lines = [line + "\n" for line in lines]  # add the newline to end
    rep.append(lines)
This example shows how to read DICOM directory.

"""

# authors : Guillaume Lemaitre <*****@*****.**>
# license : MIT

from os.path import dirname, join
from pprint import pprint

import pydicom
from pydicom.data import get_testdata_files
from pydicom.filereader import read_dicomdir

# fetch the path to the test data
filepath = get_testdata_files('DICOMDIR')[0]
print('Path to the DICOM directory: {}'.format(filepath))
# load the data
dicom_dir = read_dicomdir(filepath)
base_dir = dirname(filepath)

# go through the patient record and print information
for patient_record in dicom_dir.patient_records:
    if (hasattr(patient_record, 'PatientID') and
            hasattr(patient_record, 'PatientsName')):
        print("Patient: {}: {}".format(patient_record.PatientID,
                                       patient_record.PatientsName))
    studies = patient_record.children
    # got through each serie
    for study in studies:
        print(" " * 4 + "Study {}: {}: {}".format(study.StudyID,
示例#14
0
# authors : Guillaume Lemaitre <*****@*****.**>
# license : MIT

from __future__ import print_function

import pydicom
from pydicom.data import get_testdata_files

print(__doc__)


def list_beams(plan_dataset):
    """Summarizes the RTPLAN beam information in the dataset."""
    lines = [
        "{name:^13s} {num:^8s} {gantry:^8s} {ssd:^11s}".format(
            name="Beam name", num="Number", gantry="Gantry", ssd="SSD (cm)")
    ]
    for beam in plan_dataset.BeamSequence:
        cp0 = beam.ControlPointSequence[0]
        SSD = float(cp0.SourceToSurfaceDistance / 10)
        lines.append("{b.BeamName:^13s} {b.BeamNumber:8d} "
                     "{gantry:8.1f} {ssd:8.1f}".format(b=beam,
                                                       gantry=cp0.GantryAngle,
                                                       ssd=SSD))
    return "\n".join(lines)


filename = get_testdata_files('rtplan.dcm')[0]
dataset = pydicom.dcmread(filename)
print(list_beams(dataset))
示例#15
0
# Copyright 2008-2019 pydicom authors. See LICENSE file for details.
"""Unit tests for the pydicom.config module."""

import logging
import sys

import pytest

from pydicom import dcmread
from pydicom.config import debug
from pydicom.data import get_testdata_files


DS_PATH = get_testdata_files("CT_small.dcm")[0]
PYTEST = [int(x) for x in pytest.__version__.split('.')]


@pytest.mark.skipif(PYTEST[:2] < [3, 4], reason='no caplog')
class TestDebug(object):
    """Tests for config.debug()."""
    def setup(self):
        self.logger = logging.getLogger('pydicom')

    def teardown(self):
        # Reset to just NullHandler
        self.logger.handlers = [self.logger.handlers[0]]

    def test_default(self, caplog):
        """Test that the default logging handler is a NullHandler."""
        assert 1 == len(self.logger.handlers)
        assert isinstance(self.logger.handlers[0], logging.NullHandler)
示例#16
0
from pydicom.data import get_testdata_files
from pydicom.dataset import Dataset
from pydicom.pixel_data_handlers.util import (
    dtype_corrected_for_endianness,
    reshape_pixel_array,
    convert_color_space,
    pixel_dtype,
    get_expected_length
)
from pydicom.uid import (ExplicitVRLittleEndian,
                         UncompressedPixelTransferSyntaxes)


# 8 bit, 3 samples/pixel, 1 and 2 frame datasets
# RGB colorspace, uncompressed
RGB_8_3_1F = get_testdata_files("SC_rgb.dcm")[0]
RGB_8_3_2F = get_testdata_files("SC_rgb_2frame.dcm")[0]


# Tests with Numpy unavailable
@pytest.mark.skipif(HAVE_NP, reason='Numpy is available')
class TestNoNumpy(object):
    """Tests for the util functions without numpy."""
    def test_pixel_dtype_raises(self):
        """Test that pixel_dtype raises exception without numpy."""
        with pytest.raises(ImportError,
                           match="Numpy is required to determine the dtype"):
            pixel_dtype(None)

    def test_reshape_pixel_array_raises(self):
        """Test that reshape_pixel_array raises exception without numpy."""
示例#17
0
import pydicom
import platform
from pydicom import config
from pydicom import valuerep
from pydicom.data import get_testdata_files
from pydicom.valuerep import DS, IS
import pytest

from pydicom.valuerep import PersonName

try:
    import cPickle as pickle
except ImportError:
    import pickle

badvr_name = get_testdata_files("badVR.dcm")[0]
default_encoding = "iso8859"


@pytest.mark.skipif(
    platform.python_implementation() == "PyPy",
    reason="PyPy has trouble with this pickle",
)
class TestTM(object):
    """Unit tests for pickling TM"""
    def test_pickling(self):
        # Check that a pickled TM is read back properly
        x = pydicom.valuerep.TM("212223")
        x.original_string = "hello"
        assert "hello" == x.original_string
        assert time(21, 22, 23) == x
示例#18
0
 def setUp(self):
     self.test_file = get_testdata_files('CT_small.dcm')[0]
示例#19
0
    if HAVE_GDCM:
        import gdcm
except ImportError as e:
    HAVE_GDCM = False
    HAVE_GDCM_IN_MEMORY_SUPPORT = False
    gdcm_handler = None

try:
    import pydicom.pixel_data_handlers.numpy_handler as numpy_handler
    HAVE_NP = numpy_handler.HAVE_NP
except ImportError:
    HAVE_NP = False
    numpy_handler = None


empty_number_tags_name = get_testdata_files(
    "reportsi_with_empty_number_tags.dcm")[0]
rtplan_name = get_testdata_files("rtplan.dcm")[0]
rtdose_name = get_testdata_files("rtdose.dcm")[0]
ct_name = get_testdata_files("CT_small.dcm")[0]
mr_name = get_testdata_files("MR_small.dcm")[0]
truncated_mr_name = get_testdata_files("MR_truncated.dcm")[0]
jpeg2000_name = get_testdata_files("JPEG2000.dcm")[0]
jpeg2000_lossless_name = get_testdata_files(
    "MR_small_jp2klossless.dcm")[0]
jpeg_ls_lossless_name = get_testdata_files(
    "MR_small_jpeg_ls_lossless.dcm")[0]
jpeg_lossy_name = get_testdata_files("JPEG-lossy.dcm")[0]
jpeg_lossless_name = get_testdata_files("JPEG-LL.dcm")[0]
jpeg_lossless_odd_data_size_name = get_testdata_files(
    'SC_rgb_small_odd_jpeg.dcm')[0]
deflate_name = get_testdata_files("image_dfl.dcm")[0]
示例#20
0
#    See the file LICENSE included with this distribution, also
#    available at https://github.com/pydicom/pydicom

import unittest

import pydicom.charset
from pydicom import dicomio
from pydicom.data import get_charset_files
from pydicom.data import get_testdata_files

latin1_file = get_charset_files("chrFren.dcm")[0]
jp_file = get_charset_files("chrH31.dcm")[0]
multiPN_file = get_charset_files("chrFrenMulti.dcm")[0]
sq_encoding_file = get_charset_files("chrSQEncoding.dcm")[0]
explicit_ir6_file = get_charset_files("chrJapMultiExplicitIR6.dcm")[0]
normal_file = get_testdata_files("CT_small.dcm")[0]


class charsetTests(unittest.TestCase):
    def testLatin1(self):
        """charset: can read and decode latin_1 file........................"""
        ds = dicomio.read_file(latin1_file)
        ds.decode()
        # Make sure don't get unicode encode error on converting to string
        expected = u'Buc^J\xe9r\xf4me'
        got = ds.PatientName
        self.assertEqual(expected, got,
                         "Expected %r, got %r" % (expected, got))

    def testEncodings(self):
        test_string = u'Hello World'
示例#21
0
 def test_with(self):
     """Test Dataset.__enter__ and __exit__."""
     test_file = get_testdata_files('CT_small.dcm')[0]
     with dcmread(test_file) as ds:
         assert ds.PatientName == 'CompressedSamples^CT1'
示例#22
0
except ImportError:
    pillow_handler = None
try:
    import pydicom.pixel_data_handlers.jpeg_ls_handler as jpeg_ls_handler
    if not jpeg_ls_handler.is_this_usable:
        jpeg_ls_handler = None
except ImportError:
    jpeg_ls_handler = None
try:
    import pydicom.pixel_data_handlers.gdcm_handler as gdcm_handler
    if not gdcm_handler.is_this_usable:
        gdcm_handler = None
except ImportError:
    gdcm_handler = None

mr_name = get_testdata_files("MR_small.dcm")[0]
compressed_mr_name = get_testdata_files("MR_small_RLE.dcm")[0]
emri_name = get_testdata_files("emri_small.dcm")[0]
compressed_emri_name = get_testdata_files("emri_small_RLE.dcm")[0]
dir_name = os.path.dirname(sys.argv[0])
save_dir = os.getcwd()


class Test_RLE_transfer_syntax():
    def setup_method(self, method):
        self.mr = dcmread(mr_name)
        self.compressed_mr = dcmread(compressed_mr_name)
        self.emri = dcmread(emri_name)
        self.compressed_emri = dcmread(compressed_emri_name)
        self.original_handlers = pydicom.config.image_handlers
示例#23
0
def writeDicom(dataset, outfilename):

    datasetObj = json.loads(dataset.encode('GB18030').decode('iso8859'))

    # 读取模板Dicom文件
    filename = get_testdata_files('color-px.dcm')[0]
    ds = pydicom.dcmread(filename)

    # 当前时间
    dt = datetime.datetime.now()

    # print("Setting file meta information...")
    # Populate required values for file meta information
    # file_meta = ds.file_meta
    # file_meta.MediaStorageSOPClassUID = '1.2.840.10008.5.1.4.1.1.2'
    # file_meta.MediaStorageSOPInstanceUID = "1.2.3"
    # file_meta.ImplementationClassUID = "1.2.3.4"
    # file_meta.TransferSyntaxUID = "1.2.840.10008.1.2.5"

    print("Setting dataset values...")
    # Create the FileDataset instance (initially no data elements, but file_meta supplied)
    # ds = FileDataset(filename, {}, file_meta=file_meta, preamble=b"\0" * 128)

    img = Image.open(datasetObj['ImagePixel']['PixelData'])
    nparr = np.asarray(img)

    # Pixel Data
    # ds[0x7FE0, 0x0010] = DataElement(0x7FE00010, 'OW', img.tobytes())
    ds.PixelData = nparr.tobytes()
    # Patient's Name
    ds[0x0010, 0x0010] = DataElement(0x00100010, 'PN',
                                     datasetObj['Patient']['PatientName'])
    # Patient ID
    ds[0x0010, 0x0020] = DataElement(0x00100020, 'LO',
                                     datasetObj['Patient']['PatientID'])
    # Patient's Birth Date
    ds[0x0010, 0x0030] = DataElement(0x00100030, 'DA',
                                     datasetObj['Patient']['PatientBirthDate'])
    # Patient's Sex
    ds[0x0010, 0x0040] = DataElement(0x00100040, 'CS',
                                     datasetObj['Patient']['PatientSex'])
    # Study Date
    ds[0x0008, 0x0020] = DataElement(0x00080020, 'DA',
                                     datasetObj['GeneralStudy']['StudyDate'])
    # Study Time
    ds[0x0008, 0x0030] = DataElement(0x00080030, 'TM',
                                     datasetObj['GeneralStudy']['StudyTime'])
    # Accession Number
    ds[0x0008,
       0x0050] = DataElement(0x00080050, 'SH',
                             datasetObj['GeneralStudy']['AccessionNumber'])
    # Study Instance UID
    # ds[0x0020, 0x000D] = DataElement(0x0020000D, 'UI', '1.2.840.1.2.8.236.511020181107')
    # Study ID
    ds[0x0020, 0x0010] = DataElement(0x00200010, 'SH',
                                     datasetObj['GeneralStudy']['StudyID'])
    # Patient's Age
    ds[0x0010, 0x1010] = DataElement(0x00101010, 'AS',
                                     datasetObj['PatientStudy']['PatientAge'])
    # Patient's Size
    ds[0x0010, 0x1020] = DataElement(0x00101020, 'DS',
                                     datasetObj['PatientStudy']['PatientSize'])
    # Patient's Weight
    ds[0x0010,
       0x1030] = DataElement(0x00101030, 'DS',
                             datasetObj['PatientStudy']['PatientWeight'])
    # Series Date
    ds[0x0008, 0x0021] = DataElement(0x00080021, 'DA', dt.strftime('%Y%m%d'))
    # Series Time
    ds[0x0008, 0x0031] = DataElement(0x00080031, 'TM',
                                     dt.strftime('%H%M%S.%f'))
    # Modality
    ds[0x0008, 0x0060] = DataElement(0x00080060, 'CS',
                                     datasetObj['GeneralSeries']['Modality'])
    # Series Description
    ds[0x0008, 0x103E] = DataElement(0x0008103E, 'LO', '')
    # Performing Physician's Name
    ds[0x0008, 0x1050] = DataElement(0x00081050, 'PN', '')
    # Body Part Examined
    ds[0x0018, 0x0015] = DataElement(0x00180015, 'CS', '')
    # Series Instance UID
    # ds[0x0020, 0x000E] = DataElement(0x0020000E, 'UI', '1.2.840.1.2.8.236.51102018110715')
    # Series Number
    ds[0x0020,
       0x0011] = DataElement(0x00200011, 'IS',
                             datasetObj['GeneralSeries']['SeriesNumber'])
    # Manufacturer
    ds[0x0008,
       0x0070] = DataElement(0x00080070, 'LO',
                             datasetObj['GeneralEquipment']['Manufacturer'])
    # Institution Name
    ds[0x0008,
       0x0080] = DataElement(0x00080080, 'LO',
                             datasetObj['GeneralEquipment']['InstitutionName'])
    # Image Type
    # ds[0x0008, 0x0008] = DataElement(0x00080008, 'CS', ['DERIVED', 'SECONDARY'])   # SECONDARY
    # Instance Number
    ds[0x0020,
       0x0013] = DataElement(0x00200013, 'IS',
                             datasetObj['GeneralImage']['InstanceNumber'])
    # Window Center
    ds[0x0028, 0x1050] = DataElement(0x00281050, 'DS',
                                     datasetObj['VOILUT']['WindowCenter'])
    # Window Width
    ds[0x0028, 0x1051] = DataElement(0x00281051, 'DS',
                                     datasetObj['VOILUT']['WindowWidth'])
    # # SOP Class UID
    # ds[0x0008, 0x0016] = DataElement(0x00080016, 'UI', '1.2.840.10008.5.1.4.1.1.7')
    # # SOP Instance UID
    # ds[0x0008, 0x0018] = DataElement(0x00080018, 'UI', '1.2.840.1.2.8.236.511020181107154038')
    # Bits Allocated
    ds[0x0028, 0x0100] = DataElement(0x00280100, 'US', 8)
    # Rows
    ds[0x0028, 0x0010] = DataElement(0x00280010, 'US', 480)
    # Columns
    ds[0x0028, 0x0011] = DataElement(0x00280011, 'US', 640)
    # Photometric Interpretation
    ds[0x0028, 0x0004] = DataElement(0x00280004, 'UI', 'RGB')
    # Samples Per Pixel
    ds[0x0028, 0x0002] = DataElement(0x00280002, 'US', 0)
    # Pixel Aspect Ratio
    ds[0x0028, 0x0034] = DataElement(0x00280034, 'IS', ['1', '1'])
    # Bits Stored
    ds[0x0028, 0x0101] = DataElement(0x00280101, 'US', 8)
    # High Bit
    ds[0x0028, 0x0102] = DataElement(0x00280102, 'US', 7)

    ds.ContentDate = dt.strftime('%Y%m%d')
    ds.ContentTime = dt.strftime('%H%M%S.%f')  # long format with micro seconds

    ds.save_as(outfilename)

    # pydicom.write_file(filename, ds)

    # print('Load file {} ...'.format(outfilename))
    # ds = pydicom.dcmread(outfilename)
    # print(str(ds).encode('iso8859').decode('iso8859'))

    print("Dicom文件:{} 生成成功!".format(outfilename))
示例#24
0
from platform import python_implementation
from tempfile import TemporaryFile

import numpy as np

from pydicom import dcmread
from pydicom.dataset import Dataset
from pydicom.data import get_testdata_files
from pydicom.encaps import decode_data_sequence
from pydicom.pixel_data_handlers.numpy_handler import get_pixeldata
from pydicom.uid import ExplicitVRLittleEndian, generate_uid


# 1/1, 1 sample/pixel, 1 frame
EXPL_1_1_1F = get_testdata_files("liver_1frame.dcm")[0]
# 1/1, 1 sample/pixel, 3 frame
EXPL_1_1_3F = get_testdata_files("liver.dcm")[0]
# 8/8, 1 sample/pixel, 1 frame
EXPL_8_1_1F = get_testdata_files("OBXXXX1A.dcm")[0]
# 8/8, 1 sample/pixel, 2 frame
EXPL_8_1_2F = get_testdata_files("OBXXXX1A_2frame.dcm")[0]
# 8/8, 3 sample/pixel, 1 frame
EXPL_8_3_1F = get_testdata_files("SC_rgb.dcm")[0]
# 8/8, 3 sample/pixel, 2 frame
EXPL_8_3_2F = get_testdata_files("SC_rgb_2frame.dcm")[0]
# 16/16, 1 sample/pixel, 1 frame
EXPL_16_1_1F = get_testdata_files("MR_small.dcm")[0]
# 16/12, 1 sample/pixel, 10 frame
EXPL_16_1_10F = get_testdata_files("emri_small.dcm")[0]
# 16/16, 3 sample/pixel, 1 frame
示例#25
0
 def testJPEGlossless_odd_data_size(self):
     test_file = get_testdata_files('SC_rgb_small_odd_jpeg.dcm')[0]
     ds = dcmread(test_file)
     pixel_data = ds.pixel_array
     assert pixel_data.nbytes == 27
     assert pixel_data.shape == (3, 3, 3)
示例#26
0
from pydicom import dcmread
from pydicom.data import get_testdata_files

from pynetdicom import AE
from pynetdicom.sop_class import VerificationSOPClass, CTImageStorage

file_name = get_testdata_files('CT_small')[0]

ds = dcmread(file_name)

ae = AE()

ae.add_requested_context(VerificationSOPClass)
ae.add_requested_context(CTImageStorage)

assoc = ae.associate('localhost', 11112)

if assoc.is_established:
    status = assoc.send_c_echo()

    print(status)

    if status:
        print('C-ECHO request status: 0x{0:04x}'.format(status.Status))
    else:
        print('Connection timed out, was aborted or received invalid response')

else:
    print('Association rejected, aborted or never connected')
示例#27
0
 def test_standard_file(self):
     """charset: can read and decode standard file without special char.."""
     ds = dcmread(get_testdata_files("CT_small.dcm")[0])
     ds.decode()
     assert u'CompressedSamples^CT1' == ds.PatientName
示例#28
0
# Copyright 2008-2018 pydicom authors. See LICENSE file for details.
"""Benchmarks for the encaps module."""

from pydicom import dcmread
from pydicom.data import get_testdata_files
from pydicom.encaps import (fragment_frame, itemise_frame, encapsulate,
                            decode_data_sequence)

JP2K_10FRAME = get_testdata_files('emri_small_jpeg_2k_lossless.dcm')[0]


class TimeFragmentFrame(object):
    """Time tests for the encaps.fragment_frame function."""
    def setup(self):
        """Setup the test"""
        ds = dcmread(JP2K_10FRAME)
        self.test_data = decode_data_sequence(ds.PixelData)
        assert len(self.test_data) == 10
        self.no_runs = 1000

    def time_fragment_single(self):
        """Time fragmenting each frame into 1 fragment."""
        for ii in range(self.no_runs):
            for fragment in fragment_frame(self.test_data[0], 1):
                pass

    def time_fragment_ten(self):
        """Time fragmenting each frame into 10 fragments."""
        for ii in range(self.no_runs):
            for fragment in fragment_frame(self.test_data[0], 10):
                pass
"""

from platform import python_implementation
from tempfile import TemporaryFile

import numpy as np

from pydicom import dcmread
from pydicom.dataset import Dataset, FileMetaDataset
from pydicom.data import get_testdata_files
from pydicom.encaps import decode_data_sequence
from pydicom.pixel_data_handlers.numpy_handler import get_pixeldata
from pydicom.uid import ExplicitVRLittleEndian, generate_uid

# 1/1, 1 sample/pixel, 1 frame
EXPL_1_1_1F = get_testdata_files("liver_1frame.dcm")[0]
# 1/1, 1 sample/pixel, 3 frame
EXPL_1_1_3F = get_testdata_files("liver.dcm")[0]
# 8/8, 1 sample/pixel, 1 frame
EXPL_8_1_1F = get_testdata_files("OBXXXX1A.dcm")[0]
# 8/8, 1 sample/pixel, 2 frame
EXPL_8_1_2F = get_testdata_files("OBXXXX1A_2frame.dcm")[0]
# 8/8, 3 sample/pixel, 1 frame
EXPL_8_3_1F = get_testdata_files("SC_rgb.dcm")[0]
# 8/8, 3 sample/pixel, 1 frame, YBR_FULL_422
EXPL_8_3_1F_YBR422 = get_testdata_files('SC_ybr_full_422_uncompressed.dcm')[0]
# 8/8, 3 sample/pixel, 2 frame
EXPL_8_3_2F = get_testdata_files("SC_rgb_2frame.dcm")[0]
# 16/16, 1 sample/pixel, 1 frame
EXPL_16_1_1F = get_testdata_files("MR_small.dcm")[0]
# 16/12, 1 sample/pixel, 10 frame
示例#30
0
 def setUp(self):
     self.original_handlers = pydicom.config.image_handlers
     pydicom.config.image_handlers = [numpy_handler]
     self.odd_size_image = dcmread(
         get_testdata_files('SC_rgb_small_odd.dcm')[0])
     self.emri_small = dcmread(emri_name)
示例#31
0
from pydicom import dcmread
from pydicom.data import get_testdata_files
fpath = get_testdata_files("CT_small.dcm")[0]
print("Reading PyDICOM",fpath)

ds = dcmread(fpath)
print (type(ds))
#print(ds)

elem = ds[0x0008,0x0016]
print(elem)
print(elem.keyword)
private_elem = ds [0x0043,0x104E]
print(private_elem)
print(private_elem.keyword)

print("-----------------")
elem = ds[0x0008, 0x0016]
print(elem)
print(elem.value)
print(ds.SOPClassUID)
print(ds.ImageType)
print(ds[0x0008, 0x0008].VM)
print(ds.ImageType[1])


print("-----------------------")
#print(len(ds[0x0010, 0x1002]))

#for otherPatientSQElement in ds[0x0010, 0x1002]:
#    print(otherPatientSQElement)
示例#32
0
# Copyright 2008-2017 pydicom authors. See LICENSE file for details.
"""Tests for misc.py"""

import os

import pytest

from pydicom.data import get_testdata_files
from pydicom.misc import is_dicom, size_in_bytes

test_file = get_testdata_files('CT_small.dcm')[0]
no_meta_file = get_testdata_files('ExplVR_LitEndNoMeta.dcm')[0]


class TestMisc(object):
    def test_is_dicom(self):
        """Test the is_dicom function."""
        invalid_file = test_file.replace('CT_', 'CT')  # invalid file
        notdicom_file = os.path.abspath(__file__)  # use own file

        # valid file returns True
        assert is_dicom(test_file)

        # return false for real file but not dicom
        assert not is_dicom(notdicom_file)

        # test invalid path
        with pytest.raises(IOError):
            is_dicom(invalid_file)

        # Test no meta prefix/preamble fails
示例#33
0
try:
    import numpy as np
    from pydicom.pixel_data_handlers import numpy_handler as NP_HANDLER
    from pydicom.pixel_data_handlers.numpy_handler import get_pixeldata
    HAVE_NP = True
except ImportError:
    HAVE_NP = False
    NP_HANDLER = None

# Paths to the test datasets
# IMPL: Implicit VR Little Endian
# EXPL: Explicit VR Little Endian
# DEFL: Deflated Explicit VR Little Endian
# EXPB: Explicit VR Big Endian
# 1/1, 1 sample/pixel, 1 frame
EXPL_1_1_1F = get_testdata_files("liver_1frame.dcm")[0]
EXPB_1_1_1F = get_testdata_files("liver_expb_1frame.dcm")[0]
# 1/1, 1 sample/pixel, 3 frame
EXPL_1_1_3F = get_testdata_files("liver.dcm")[0]
EXPB_1_1_3F = get_testdata_files("liver_expb.dcm")[0]
# 1/1, 3 sample/pixel, 1 frame
EXPL_1_3_1F = None
EXPB_1_3_1F = None
# 1/1, 3 sample/pixel, XXX frame
EXPL_1_3_XF = None
EXPB_1_3_XF = None
# 8/8, 1 sample/pixel, 1 frame
DEFL_8_1_1F = get_testdata_files("image_dfl.dcm")[0]
EXPL_8_1_1F = get_testdata_files("OBXXXX1A.dcm")[0]
EXPB_8_1_1F = get_testdata_files("OBXXXX1A_expb.dcm")[0]
# 8/8, 1 sample/pixel, 2 frame
示例#34
0
# Copyright 2008-2017 pydicom authors. See LICENSE file for details.
"""Test for filebase.py"""

from io import BytesIO

import pytest

from pydicom.data import get_testdata_files
from pydicom.filebase import DicomIO, DicomFileLike, DicomFile, DicomBytesIO
from pydicom.tag import Tag

TEST_FILE = get_testdata_files('CT_small.dcm')[0]


class TestDicomIO(object):
    """Test filebase.DicomIO class"""
    def test_init(self):
        """Test __init__"""
        # All the subclasses override this anyway
        fp = DicomIO()
        assert fp.is_implicit_VR

    def test_read_le_tag(self):
        """Test DicomIO.read_le_tag indirectly"""
        # Tags are 2 + 2 = 4 bytes
        bytestream = b'\x01\x02\x03\x04\x05\x06'
        fp = DicomBytesIO(bytestream)
        fp.is_little_endian = True
        assert Tag(fp.read_le_tag()) == 0x02010403

    def test_read_be_tag(self):
    import pydicom.pixel_data_handlers.pillow_handler as pillow_handler
    have_pillow_jpeg_plugin = pillow_handler.have_pillow_jpeg_plugin
    have_pillow_jpeg2000_plugin = \
        pillow_handler.have_pillow_jpeg2000_plugin
except ImportError:
    have_pillow_handler = False
try:
    import pydicom.pixel_data_handlers.jpeg_ls_handler as jpeg_ls_handler
except ImportError:
    jpeg_ls_handler = None
try:
    import pydicom.pixel_data_handlers.gdcm_handler as gdcm_handler
except ImportError:
    gdcm_handler = None

mr_name = get_testdata_files("MR_small.dcm")[0]
jpeg_ls_lossless_name = get_testdata_files("MR_small_jpeg_ls_lossless.dcm")[0]
emri_name = get_testdata_files("emri_small.dcm")[0]
emri_jpeg_ls_lossless = get_testdata_files(
    "emri_small_jpeg_ls_lossless.dcm")[0]
dir_name = os.path.dirname(sys.argv[0])
save_dir = os.getcwd()


class Test_JPEG_LS_Lossless_transfer_syntax():
    def setup_method(self, method):
        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
示例#36
0
 def test_with(self):
     """Test Dataset.__enter__ and __exit__."""
     test_file = get_testdata_files('CT_small.dcm')[0]
     with dcmread(test_file) as ds:
         assert ds.PatientName == 'CompressedSamples^CT1'
示例#37
0
try:
    from PIL import Image as PILImg
except ImportError:
    # If that failed, try the alternate import syntax for PIL.
    try:
        import Image as PILImg
    except ImportError:
        # Neither worked, so it's likely not installed.
        PILImg = None

have_numpy = numpy is not None
have_jpeg_ls = jpeg_ls is not None
have_pillow = PILImg is not None

empty_number_tags_name = get_testdata_files(
    "reportsi_with_empty_number_tags.dcm")[0]
rtplan_name = get_testdata_files("rtplan.dcm")[0]
rtdose_name = get_testdata_files("rtdose.dcm")[0]
ct_name = get_testdata_files("CT_small.dcm")[0]
mr_name = get_testdata_files("MR_small.dcm")[0]
truncated_mr_name = get_testdata_files("MR_truncated.dcm")[0]
jpeg2000_name = get_testdata_files("JPEG2000.dcm")[0]
jpeg2000_lossless_name = get_testdata_files("MR_small_jp2klossless.dcm")[0]
jpeg_ls_lossless_name = get_testdata_files("MR_small_jpeg_ls_lossless.dcm")[0]
jpeg_lossy_name = get_testdata_files("JPEG-lossy.dcm")[0]
jpeg_lossless_name = get_testdata_files("JPEG-LL.dcm")[0]
deflate_name = get_testdata_files("image_dfl.dcm")[0]
rtstruct_name = get_testdata_files("rtstruct.dcm")[0]
priv_SQ_name = get_testdata_files("priv_SQ.dcm")
# be sure that we don't pick up the nested_priv_sq
priv_SQ_name = [
示例#38
0
try:
    from pydicom.overlay_data_handlers import numpy_handler as NP_HANDLER
    from pydicom.overlay_data_handlers.numpy_handler import (
        get_overlay_array,
        reshape_overlay_array,
        get_expected_length,
    )
except ImportError:
    NP_HANDLER = None

# Paths to the test datasets
# EXPL: Explicit VR Little Endian
# Overlay Data
# 1/1, 1 sample/pixel, 1 frame
EXPL_1_1_1F = get_testdata_files("MR-SIEMENS-DICOM-WithOverlays.dcm")[0]
# 1/1, 1 sample/pixel, N frame
EXPL_1_1_3F = None
# No Overlay Data
# 16/16, 1 sample/pixel, 1 frame
EXPL_16_1_1F = get_testdata_files("MR_small.dcm")[0]

# Transfer syntaxes supported by other handlers
# JPEG Baseline (Process 1)
JPEG_BASELINE_1 = get_testdata_files("SC_rgb_jpeg_dcmtk.dcm")[0]
# JPEG Baseline (Process 2 and 4)
JPEG_EXTENDED_2 = get_testdata_files("JPEG-lossy.dcm")[0]
# JPEG Lossless (Process 14)
JPEG_LOSSLESS_14 = None
# JPEG Lossless (Process 14, Selection Value 1)
JPEG_LOSSLESS_14_1 = get_testdata_files("SC_rgb_jpeg_gdcm.dcm")[0]
示例#39
0
"""
Read DICOM and ploting using matplotlib
본 예제는 matplotlib을 통해 DICOM 파일을 시각화하고, 몇가지 정보를 print하는 예제입니다.
"""
import matplotlib.pyplot as plt
import pydicom
from pydicom.data import get_testdata_files

print(__doc__)

filename = get_testdata_files('CT_small.dcm')[0]
dataset = pydicom.dcmread(filename)

print()
print("Filename...................:", filename)
print("Storage type...............:", dataset.SOPClassUID)
print()

pat_name = dataset.PatientName
display_name = pat_name.family_name + ', ' + pat_name.given_name
print("Patient's name.............:", display_name)
print("Patient id.................:", dataset.PatientID)
print("Modality...................:", dataset.Modality)
print("Study Date.................:", dataset.StudyDate)

if 'PixelData' in dataset:
    rows = int(dataset.Rows)
    cols = int(dataset.Columns)
    print("Image size.................: {rows:d} x {cols:d}, {size:d} bytes".format(
        rows=rows, cols=cols, size=len(dataset.PixelData)))
    if 'PixelSpacing' in dataset:
示例#40
0
 def setUp(self):
     self.test_file = get_testdata_files('CT_small.dcm')[0]
示例#41
0
# Copyright 2008-2017 pydicom authors. See LICENSE file for details.
"""Test for dicomdir.py"""

import pytest

from pydicom.data import get_testdata_files
from pydicom.dicomdir import DicomDir
from pydicom.errors import InvalidDicomError
from pydicom import read_file


TEST_FILE = get_testdata_files('DICOMDIR')[0]


class TestDicomDir(object):
    """Test dicomdir.DicomDir class"""
    def test_read_file(self):
        """Test creation of DicomDir instance using filereader.read_file"""
        ds = read_file(TEST_FILE)
        assert isinstance(ds, DicomDir)

    def test_invalid_sop_file_meta(self):
        """Test exception raised if SOP Class is not Media Storage Directory"""
        ds = read_file(get_testdata_files('CT_small.dcm')[0])
        with pytest.raises(InvalidDicomError,
                           match="SOP Class is not Media Storage "
                                 "Directory \(DICOMDIR\)"):
            DicomDir("some_name", ds, b'\x00' * 128, ds.file_meta, True, True)

    def test_invalid_sop_no_file_meta(self):
        """Test exception raised if invalid sop class but no file_meta"""
示例#42
0
.. note::

   This example requires the Numpy library to manipulate the pixel data.

"""

# authors : Guillaume Lemaitre <*****@*****.**>
# license : MIT

import pydicom
from pydicom.data import get_testdata_files

print(__doc__)

# FIXME: add a full-sized MR image in the testing data
filename = get_testdata_files('MR_small.dcm')[0]
ds = pydicom.dcmread(filename)

# get the pixel information into a numpy array
data = ds.pixel_array
print('The image has {} x {} voxels'.format(data.shape[0],
                                            data.shape[1]))
data_downsampling = data[::8, ::8]
print('The downsampled image has {} x {} voxels'.format(
    data_downsampling.shape[0], data_downsampling.shape[1]))

# copy the data back to the original data set
ds.PixelData = data_downsampling.tobytes()
# update the information regarding the shape of the data array
ds.Rows, ds.Columns = data_downsampling.shape
# Copyright 2008-2018 pydicom authors. See LICENSE file for details.
"""Encoding benchmarks for the rle_handler module."""

import numpy as np

from pydicom import dcmread
from pydicom.data import get_testdata_files
from pydicom.pixel_data_handlers.rle_handler import (
    rle_encode_frame,
    _rle_encode_segment,
)

# 8/8-bit, 1 sample/pixel, 1 frame
EXPL_8_1_1F = get_testdata_files("OBXXXX1A.dcm")[0]
# 8/8-bit, 3 sample/pixel, 1 frame
EXPL_8_3_1F = get_testdata_files("SC_rgb.dcm")[0]
# 16/16-bit, 1 sample/pixel, 1 frame
EXPL_16_1_1F = get_testdata_files("MR_small.dcm")[0]
# 16/16-bit, 3 sample/pixel, 1 frame
EXPL_16_3_1F = get_testdata_files("SC_rgb_16bit.dcm")[0]
# 32/32-bit, 1 sample/pixel, 1 frame
EXPL_32_1_1F = get_testdata_files("rtdose_1frame.dcm")[0]
# 32/32-bit, 3 sample/pixel, 1 frame
EXPL_32_3_1F = get_testdata_files("SC_rgb_32bit.dcm")[0]


class TimeRLEEncodeSegment:
    """Time tests for rle_handler._rle_encode_segment."""
    def setup(self):
        ds = dcmread(EXPL_8_1_1F)
        self.arr = ds.pixel_array
This example shows how to read DICOM directory.

"""

# authors : Guillaume Lemaitre <*****@*****.**>
# license : MIT

from os.path import dirname, join
from pprint import pprint

import pydicom
from pydicom.data import get_testdata_files
from pydicom.filereader import read_dicomdir

# fetch the path to the test data
filepath = get_testdata_files('DICOMDIR')[0]
print('Path to the DICOM directory: {}'.format(filepath))
# load the data
dicom_dir = read_dicomdir(filepath)
base_dir = dirname(filepath)

# go through the patient record and print information
for patient_record in dicom_dir.patient_records:
    if (hasattr(patient_record, 'PatientID') and
            hasattr(patient_record, 'PatientName')):
        print("Patient: {}: {}".format(patient_record.PatientID,
                                       patient_record.PatientName))
    studies = patient_record.children
    # got through each serie
    for study in studies:
        print(" " * 4 + "Study {}: {}: {}".format(study.StudyID,
示例#45
0
import pydicom
from pydicom.data import get_testdata_files

filename = get_testdata_files(
    "D://dicom//202003//05//5007025//CR//1.2.840.114315.1.2.630.20200305062807.9392.1.1.dcm"
)[0]
ds = pydicom.dcmread(filename)
示例#46
0
if not in_py2:
    from pydicom.valuerep import PersonName3 as PersonNameUnicode

    PersonName = PersonNameUnicode
else:
    from pydicom.valuerep import (
        PersonName,
        PersonNameUnicode
    )

try:
    import cPickle as pickle
except ImportError:
    import pickle

badvr_name = get_testdata_files("badVR.dcm")[0]
default_encoding = 'iso8859'


@pytest.mark.skipif(platform.python_implementation() == 'PyPy',
                    reason="PyPy has trouble with this pickle")
class TestTM(object):
    """Unit tests for pickling TM"""

    def test_pickling(self):
        # Check that a pickled TM is read back properly
        x = pydicom.valuerep.TM("212223")
        x.original_string = 'hello'
        assert 'hello' == x.original_string
        assert time(21, 22, 23) == x
        data1_string = pickle.dumps(x)
    import pydicom.pixel_data_handlers.pillow_handler as pillow_handler
    have_pillow_jpeg_plugin = pillow_handler.have_pillow_jpeg_plugin
    have_pillow_jpeg2000_plugin = \
        pillow_handler.have_pillow_jpeg2000_plugin
except ImportError:
    have_pillow_handler = False
try:
    import pydicom.pixel_data_handlers.jpeg_ls_handler as jpeg_ls_handler
except ImportError:
    jpeg_ls_handler = None
try:
    import pydicom.pixel_data_handlers.gdcm_handler as gdcm_handler
except ImportError:
    gdcm_handler = None

mr_name = get_testdata_files("MR_small.dcm")[0]
jpeg_ls_lossless_name = get_testdata_files("MR_small_jpeg_ls_lossless.dcm")[0]
emri_name = get_testdata_files("emri_small.dcm")[0]
emri_jpeg_ls_lossless = get_testdata_files(
    "emri_small_jpeg_ls_lossless.dcm")[0]
dir_name = os.path.dirname(sys.argv[0])
save_dir = os.getcwd()


class Test_JPEG_LS_Lossless_transfer_syntax():
    def setup_method(self, method):
        self.jpeg_ls_lossless = dcmread(jpeg_ls_lossless_name)
        self.mr_small = dcmread(mr_name)
        self.emri_jpeg_ls_lossless = dcmread(emri_jpeg_ls_lossless)
        self.emri_small = dcmread(emri_name)
        self.original_handlers = pydicom.config.image_handlers
示例#48
0
This examples illustrates how to find the differences between two DICOM files.

"""

# authors : Guillaume Lemaitre <*****@*****.**>
# license : MIT

import difflib

import pydicom
from pydicom.data import get_testdata_files

print(__doc__)

filename_mr = get_testdata_files('MR_small.dcm')[0]
filename_ct = get_testdata_files('CT_small.dcm')[0]

datasets = tuple([pydicom.dcmread(filename, force=True)
                  for filename in (filename_mr, filename_ct)])

# difflib compare functions require a list of lines, each terminated with
# newline character massage the string representation of each dicom dataset
# into this form:
rep = []
for dataset in datasets:
    lines = str(dataset).split("\n")
    lines = [line + "\n" for line in lines]  # add the newline to end
    rep.append(lines)

示例#49
0
# Copyright 2008-2018 pydicom authors. See LICENSE file for details.
"""Tests for misc.py"""

import os

import pytest

from pydicom.data import get_testdata_files
from pydicom.misc import is_dicom, size_in_bytes

test_file = get_testdata_files('CT_small.dcm')[0]
no_meta_file = get_testdata_files('ExplVR_LitEndNoMeta.dcm')[0]


class TestMisc(object):
    def test_is_dicom(self):
        """Test the is_dicom function."""
        invalid_file = test_file.replace('CT_', 'CT')  # invalid file
        notdicom_file = os.path.abspath(__file__)  # use own file

        # valid file returns True
        assert is_dicom(test_file)

        # return false for real file but not dicom
        assert not is_dicom(notdicom_file)

        # test invalid path
        with pytest.raises(IOError):
            is_dicom(invalid_file)

        # Test no meta prefix/preamble fails
示例#50
0
def on_c_get(ds, context, info):
    """Respond to a C-GET request Identifier `ds`.

    Parameters
    ----------
    ds : pydicom.dataset.Dataset
        The Identifier dataset sent by the peer.
    context : presentation.PresentationContextTuple
        The presentation context that the C-GET message was sent under.
    info : dict
        A dict containing information about the current association.

    Yields
    ------
    int
        The first yielded value should be the total number of C-STORE
        sub-operations necessary to complete the C-GET operation. In other
        words, this is the number of matching SOP Instances to be sent to
        the peer.
    status : pydicom.dataset.Dataset or int
        The status returned to the peer AE in the C-GET response. Must be a
        valid C-GET status value for the applicable Service Class as either
        an ``int`` or a ``Dataset`` object containing (at a minimum) a
        (0000,0900) *Status* element. If returning a Dataset object then
        it may also contain optional elements related to the Status (as in
        DICOM Standard Part 7, Annex C).
    dataset : pydicom.dataset.Dataset or None
        If the status is 'Pending' then yield the ``Dataset`` to send to
        the peer via a C-STORE sub-operation over the current association.

        If the status is 'Failed', 'Warning' or 'Cancel' then yield a
        ``Dataset`` with a (0008,0058) *Failed SOP Instance UID List*
        element containing a list of the C-STORE sub-operation SOP Instance
        UIDs for which the C-GET operation has failed.

        If the status is 'Success' then yield ``None``, although yielding a
        final 'Success' status is not required and will be ignored if
        necessary
    """
    if 'QueryRetrieveLevel' not in ds:
        # Failure
        yield 0xC000, None
        return

    # Import stored SOP Instances
    instances = []
    matching = []
    filename = get_testdata_files('CT_small.dcm')[0]
    filename2 = get_testdata_files("rtplan.dcm")[0]
    instances.append(dcmread(filename))
    instances.append(dcmread(filename2))
    """
    print(filename)
    fdir = '/path/to/directory'
    for fpath in os.listdir(fdir):
        instances.append(dcmread(os.path.join(fdir, fpath)))
    """

    if ds.QueryRetrieveLevel == 'PATIENT':
        if 'PatientID' in ds:
            matching = [
                inst for inst in instances if inst.PatientID == ds.PatientID
            ]

        # Skip the other possible attributes...

    # Skip the other QR levels...

    # Yield the total number of C-STORE sub-operations required
    yield len(instances)
    # Yield the matching instances
    for instance in matching:
        # Pending
        yield (0xFF00, instance)
示例#51
0
# Copyright 2008-2018 pydicom authors. See LICENSE file for details.
"""Decoding benchmarks for the rle_handler module."""

from pydicom import dcmread
from pydicom.data import get_testdata_files
from pydicom.encaps import decode_data_sequence
from pydicom.pixel_data_handlers.rle_handler import (
    get_pixeldata,
    _rle_decode_frame,
)

# 8/8-bit, 1 sample/pixel, 1 frame
OB_RLE_1F = get_testdata_files("OBXXXX1A_rle.dcm")[0]
# 8/8-bit, 1 sample/pixel, 2 frame
OB_RLE_2F = get_testdata_files("OBXXXX1A_rle_2frame.dcm")[0]
# 8/8-bit, 3 sample/pixel, 1 frame
SC_RLE_1F = get_testdata_files("SC_rgb_rle.dcm")[0]
# 8/8-bit, 3 sample/pixel, 2 frame
SC_RLE_2F = get_testdata_files("SC_rgb_rle_2frame.dcm")[0]
# 16/16-bit, 1 sample/pixel, 1 frame
MR_RLE_1F = get_testdata_files("MR_small_RLE.dcm")[0]
# 16/16-bit, 3 sample/pixel, 1 frame
SC_RLE_16_1F = get_testdata_files("SC_rgb_rle_16bit.dcm")[0]
# 16/16-bit, 3 sample/pixel, 2 frame
SC_RLE_16_2F = get_testdata_files("SC_rgb_rle_16bit_2frame.dcm")[0]
# 16/12-bit, 1 sample/pixel, 10 frame
EMRI_RLE_10F = get_testdata_files("emri_small_RLE.dcm")[0]
# 32/32-bit, 1 sample/pixel, 1 frame
RTDOSE_RLE_1F = get_testdata_files("rtdose_rle_1frame.dcm")[0]
# 32/32-bit, 3 sample/pixel, 1 frame
SC_RLE_32_1F = get_testdata_files("SC_rgb_rle_32bit.dcm")[0]
示例#52
0
 def testJPEGlossless_odd_data_size(self):
     test_file = get_testdata_files('SC_rgb_small_odd_jpeg.dcm')[0]
     ds = dcmread(test_file)
     pixel_data = ds.pixel_array
     assert pixel_data.nbytes == 27
     assert pixel_data.shape == (3, 3, 3)
示例#53
0
import unittest

from pydicom.data import get_charset_files
from pydicom.data import get_testdata_files
import pydicom.charset
from pydicom.dataelem import DataElement
from pydicom import dcmread


latin1_file = get_charset_files("chrFren.dcm")[0]
jp_file = get_charset_files("chrH31.dcm")[0]
multiPN_file = get_charset_files("chrFrenMulti.dcm")[0]
sq_encoding_file = get_charset_files("chrSQEncoding.dcm")[0]
sq_encoding1_file = get_charset_files("chrSQEncoding1.dcm")[0]
explicit_ir6_file = get_charset_files("chrJapMultiExplicitIR6.dcm")[0]
normal_file = get_testdata_files("CT_small.dcm")[0]


class CharsetTests(unittest.TestCase):
    def test_latin1(self):
        """charset: can read and decode latin_1 file........................"""
        ds = dcmread(latin1_file)
        ds.decode()
        # Make sure don't get unicode encode error on converting to string
        expected = u'Buc^J\xe9r\xf4me'
        got = ds.PatientName
        self.assertEqual(expected, got,
                         "Expected %r, got %r" % (expected, got))

    def test_encodings(self):
        test_string = u'Hello World'
示例#54
0
# Copyright 2008-2017 pydicom authors. See LICENSE file for details.
"""Test for dicomdir.py"""

import pytest

from pydicom.data import get_testdata_files
from pydicom.dicomdir import DicomDir
from pydicom.errors import InvalidDicomError
from pydicom import read_file

TEST_FILE = get_testdata_files('DICOMDIR')[0]


class TestDicomDir(object):
    """Test dicomdir.DicomDir class"""
    def test_read_file(self):
        """Test creation of DicomDir instance using filereader.read_file"""
        ds = read_file(TEST_FILE)
        assert isinstance(ds, DicomDir)

    def test_invalid_sop_file_meta(self):
        """Test exception raised if SOP Class is not Media Storage Directory"""
        ds = read_file(get_testdata_files('CT_small.dcm')[0])
        with pytest.raises(InvalidDicomError,
                           match="SOP Class is not Media Storage "
                           "Directory \(DICOMDIR\)"):
            DicomDir("some_name", ds, b'\x00' * 128, ds.file_meta, True, True)

    def test_invalid_sop_no_file_meta(self):
        """Test exception raised if invalid sop class but no file_meta"""
        ds = read_file(get_testdata_files('CT_small.dcm')[0])
示例#55
0
        get_pixeldata,
        unpack_bits,
        pack_bits,
        pixel_dtype,
    )
except ImportError:
    NP_HANDLER = None


# Paths to the test datasets
# IMPL: Implicit VR Little Endian
# EXPL: Explicit VR Little Endian
# DEFL: Deflated Explicit VR Little Endian
# EXPB: Explicit VR Big Endian
# 1/1, 1 sample/pixel, 1 frame
EXPL_1_1_1F = get_testdata_files("liver_1frame.dcm")[0]
EXPB_1_1_1F = get_testdata_files("liver_expb_1frame.dcm")[0]
# 1/1, 1 sample/pixel, 3 frame
EXPL_1_1_3F = get_testdata_files("liver.dcm")[0]
EXPB_1_1_3F = get_testdata_files("liver_expb.dcm")[0]
# 1/1, 3 sample/pixel, 1 frame
EXPL_1_3_1F = None
EXPB_1_3_1F = None
# 1/1, 3 sample/pixel, XXX frame
EXPL_1_3_XF = None
EXPB_1_3_XF = None
# 8/8, 1 sample/pixel, 1 frame
DEFL_8_1_1F = get_testdata_files("image_dfl.dcm")[0]
EXPL_8_1_1F = get_testdata_files("OBXXXX1A.dcm")[0]
EXPB_8_1_1F = get_testdata_files("OBXXXX1A_expb.dcm")[0]
# 8/8, 1 sample/pixel, 2 frame
示例#56
0
    have_numpy_handler = False
try:
    import pydicom.pixel_data_handlers.pillow_handler as pillow_handler
    have_pillow_jpeg_plugin = pillow_handler.have_pillow_jpeg_plugin
    have_pillow_jpeg2000_plugin = \
        pillow_handler.have_pillow_jpeg2000_plugin
except ImportError:
    have_pillow_handler = False

test_pillow_decoder = have_numpy_handler and have_pillow_handler
test_pillow_jpeg_decoder = (test_pillow_decoder and
                            have_pillow_jpeg_plugin)
test_pillow_jpeg2000_decoder = (test_pillow_decoder and
                                have_pillow_jpeg2000_plugin)

empty_number_tags_name = get_testdata_files(
    "reportsi_with_empty_number_tags.dcm")[0]
rtplan_name = get_testdata_files("rtplan.dcm")[0]
rtdose_name = get_testdata_files("rtdose.dcm")[0]
ct_name = get_testdata_files("CT_small.dcm")[0]
mr_name = get_testdata_files("MR_small.dcm")[0]
truncated_mr_name = get_testdata_files("MR_truncated.dcm")[0]
jpeg2000_name = get_testdata_files("JPEG2000.dcm")[0]
jpeg2000_lossless_name = get_testdata_files(
    "MR_small_jp2klossless.dcm")[0]
jpeg_ls_lossless_name = get_testdata_files(
    "MR_small_jpeg_ls_lossless.dcm")[0]
jpeg_lossy_name = get_testdata_files("JPEG-lossy.dcm")[0]
jpeg_lossless_name = get_testdata_files("JPEG-LL.dcm")[0]
deflate_name = get_testdata_files("image_dfl.dcm")[0]
rtstruct_name = get_testdata_files("rtstruct.dcm")[0]
priv_SQ_name = get_testdata_files("priv_SQ.dcm")[0]
示例#57
0
try:
    from PIL import Image as PILImg
except ImportError:
    # If that failed, try the alternate import syntax for PIL.
    try:
        import Image as PILImg
    except ImportError:
        # Neither worked, so it's likely not installed.
        PILImg = None

have_numpy = numpy is not None
have_jpeg_ls = jpeg_ls is not None
have_pillow = PILImg is not None

empty_number_tags_name = get_testdata_files(
    "reportsi_with_empty_number_tags.dcm")[0]
rtplan_name = get_testdata_files("rtplan.dcm")[0]
rtdose_name = get_testdata_files("rtdose.dcm")[0]
ct_name = get_testdata_files("CT_small.dcm")[0]
mr_name = get_testdata_files("MR_small.dcm")[0]
truncated_mr_name = get_testdata_files("MR_truncated.dcm")[0]
jpeg2000_name = get_testdata_files("JPEG2000.dcm")[0]
jpeg2000_lossless_name = get_testdata_files("MR_small_jp2klossless.dcm")[0]
jpeg_ls_lossless_name = get_testdata_files("MR_small_jpeg_ls_lossless.dcm")[0]
jpeg_lossy_name = get_testdata_files("JPEG-lossy.dcm")[0]
jpeg_lossless_name = get_testdata_files("JPEG-LL.dcm")[0]
deflate_name = get_testdata_files("image_dfl.dcm")[0]
rtstruct_name = get_testdata_files("rtstruct.dcm")[0]
priv_SQ_name = get_testdata_files("priv_SQ.dcm")
# be sure that we don't pick up the nested_priv_sq
priv_SQ_name = [filename
示例#58
0
 def test_standard_file(self):
     """charset: can read and decode standard file without special char.."""
     ds = dcmread(get_testdata_files("CT_small.dcm")[0])
     ds.decode()
     assert 'CompressedSamples^CT1' == ds.PatientName
示例#59
0
# Copyright 2008-2017 pydicom authors. See LICENSE file for details.
"""Test for filebase.py"""

from io import BytesIO

import pytest

from pydicom.data import get_testdata_files
from pydicom.filebase import DicomIO, DicomFileLike, DicomFile, DicomBytesIO
from pydicom.tag import Tag


TEST_FILE = get_testdata_files('CT_small.dcm')[0]


class TestDicomIO(object):
    """Test filebase.DicomIO class"""
    def test_init(self):
        """Test __init__"""
        # All the subclasses override this anyway
        fp = DicomIO()
        assert fp.is_implicit_VR

    def test_read_le_tag(self):
        """Test DicomIO.read_le_tag indirectly"""
        # Tags are 2 + 2 = 4 bytes
        bytestream = b'\x01\x02\x03\x04\x05\x06'
        fp = DicomBytesIO(bytestream)
        fp.is_little_endian = True
        assert Tag(fp.read_le_tag()) == 0x02010403
try:
    from pydicom.pixel_data_handlers import rle_handler as RLE_HANDLER
    from pydicom.pixel_data_handlers.rle_handler import (
        get_pixeldata,
        _rle_decode_frame,
        _rle_decode_segment,
        _parse_rle_header,
    )
    HAVE_RLE = RLE_HANDLER.HAVE_RLE
except ImportError:
    HAVE_RLE = False
    RLE_HANDLER = None

# Paths to the test datasets
# 8/8-bit, 1 sample/pixel, 1 frame
OB_EXPL_LITTLE_1F = get_testdata_files("OBXXXX1A.dcm")[0]
OB_RLE_1F = get_testdata_files("OBXXXX1A_rle.dcm")[0]
# 8/8-bit, 1 sample/pixel, 2 frame
OB_EXPL_LITTLE_2F = get_testdata_files("OBXXXX1A_2frame.dcm")[0]
OB_RLE_2F = get_testdata_files("OBXXXX1A_rle_2frame.dcm")[0]
# 8/8-bit, 3 sample/pixel, 1 frame
SC_EXPL_LITTLE_1F = get_testdata_files("SC_rgb.dcm")[0]
SC_RLE_1F = get_testdata_files("SC_rgb_rle.dcm")[0]
# 8/8-bit, 3 sample/pixel, 2 frame
SC_EXPL_LITTLE_2F = get_testdata_files("SC_rgb_2frame.dcm")[0]
SC_RLE_2F = get_testdata_files("SC_rgb_rle_2frame.dcm")[0]
# 16/16-bit, 1 sample/pixel, 1 frame
MR_EXPL_LITTLE_1F = get_testdata_files("MR_small.dcm")[0]
MR_RLE_1F = get_testdata_files("MR_small_RLE.dcm")[0]
# 16/12-bit, 1 sample/pixel, 10 frame
EMRI_EXPL_LITTLE_10F = get_testdata_files("emri_small.dcm")[0]