How to use the pydicom.compat function in pydicom

To help you get started, we’ve selected a few pydicom examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github pydicom / pydicom / pydicom / charset.py View on Github external
PersonNameUnicode(value, encodings)
                    for value in data_element.value
                ]
    if data_element.VR in text_VRs:
        # You can't re-decode unicode (string literals in py3)
        if data_element.VM == 1:
            if isinstance(data_element.value, compat.text_type):
                return
            data_element.value = decode_string(data_element.value, encodings,
                                               TEXT_VR_DELIMS)
        else:

            output = list()

            for value in data_element.value:
                if isinstance(value, compat.text_type):
                    output.append(value)
                else:
                    output.append(decode_string(value, encodings,
                                                TEXT_VR_DELIMS))

            data_element.value = output
github pydicom / pydicom / pydicom / dataelem.py View on Github external
def VM(self):
        """Return the value multiplicity of the element as :class:`int`."""
        if self.value is None:
            return 0
        if isinstance(self.value, (compat.char_types, PersonName)):
            return 1 if self.value else 0
        try:
            iter(self.value)
        except TypeError:
            return 1
        return len(self.value)
github pydicom / pydicom / pydicom / contrib / imViewer_Simple.py View on Github external
def recurse_tree(self, ds, parent, hide=False):
        """ order the dicom tags """
        for data_element in ds:
            if isinstance(data_element.value, compat.text_type):
                text = compat.text_type(data_element)
                ip = self.dsTreeView.AppendItem(parent, text=text)
            else:
                ip = self.dsTreeView.AppendItem(parent, text=str(data_element))

            if data_element.VR == "SQ":
                for i, ds in enumerate(data_element.value):
                    item_describe = data_element.name.replace(" Sequence", "")
                    item_text = "%s %d" % (item_describe, i + 1)
                    rjust = item_text.rjust(128)
                    parentNodeID = self.dsTreeView.AppendItem(ip, text=rjust)
                    self.recurse_tree(ds, parentNodeID)
github pydicom / pydicom / pydicom / filereader.py View on Github external
>>> ds = pydicom.dcmread("rtplan.dcm")
    >>> ds.PatientName

    Read and return a dataset not in accordance with the DICOM File Format:

    >>> ds = pydicom.dcmread("rtplan.dcm", force=True)
    >>> ds.PatientName

    Use within a context manager:

    >>> with pydicom.dcmread("rtplan.dcm") as ds:
    >>>     ds.PatientName
    """
    # Open file if not already a file object
    caller_owns_file = True
    if isinstance(fp, compat.string_types):
        # caller provided a file name; we own the file handle
        caller_owns_file = False
        try:
            logger.debug(u"Reading file '{0}'".format(fp))
        except Exception:
            logger.debug("Reading file '{0}'".format(fp))
        fp = open(fp, 'rb')

    if config.debugging:
        logger.debug("\n" + "-" * 80)
        logger.debug("Call to dcmread()")
        msg = ("filename:'%s', defer_size='%s', "
               "stop_before_pixels=%s, force=%s, specific_tags=%s")
        logger.debug(msg % (fp.name, defer_size, stop_before_pixels,
                            force, specific_tags))
        if caller_owns_file:
github pydicom / pydicom / pydicom / contrib / pydicom_series.py View on Github external
def _progressCallback(progress):
    """ The default callback for displaying progress. """
    if isinstance(progress, compat.string_types):
        _progressBar.Start(progress)
        _progressBar._t0 = time.time()
    elif progress is None:
        dt = time.time() - _progressBar._t0
        _progressBar.Finish('%2.2f seconds' % dt)
    else:
        _progressBar.Update(progress)
github pydicom / pydicom / pydicom / tag.py View on Github external
raise ValueError("'{}' is not a valid int or DICOM keyword"
                                 .format(arg))
    # Single int parameter
    else:
        long_value = arg
        if long_value > 0xFFFFFFFF:
            raise OverflowError("Tags are limited to 32-bit length; tag {0!r}"
                                .format(long_value))

    if long_value < 0:
        raise ValueError("Tags must be positive.")

    return BaseTag(long_value)


if compat.in_py2:
    # May get an overflow error with int if sys.maxsize < 0xFFFFFFFF
    BaseTag_base_class = long
else:
    BaseTag_base_class = int


class BaseTag(BaseTag_base_class):
    """Represents a DICOM element (group, element) tag.

    If using python 2.7 then tags are represented as a long, while for python
    3 they are represented as an int.

    Attributes
    ----------
    element : int
        The element number of the tag.
github pydicom / pydicom / pydicom / examples / dicomtree.py View on Github external
# dicomtree.py
"""Show a dicom file using a hierarchical tree in a graphical window"""
from __future__ import print_function
# Copyright (c) 2008-2012 Darcy Mason
# This file is part of pydicom, relased under an MIT license.
#    See the file license.txt included with this distribution, also
#    available at https://github.com/darcymason/pydicom

usage = "Usage: python dicomtree.py dicom_filename"

from pydicom import compat

if compat.in_py2:
    import Tix as tkinter_tix
else:
    import tkinter.tix as tkinter_tix

def RunTree(w, filename):
    top = tkinter_tix.Frame(w, relief=tkinter_tix.RAISED, bd=1)
    tree = tkinter_tix.Tree(top, options="hlist.columns 2")
    tree.pack(expand=1, fill=tkinter_tix.BOTH, padx=10, pady=10,
              side=tkinter_tix.LEFT)
    # print(tree.hlist.keys())   # use to see the available configure() options
    tree.hlist.configure(bg='white', font='Courier 10', indent=30)
    tree.hlist.configure(selectbackground='light yellow', gap=150)

    box = tkinter_tix.ButtonBox(w, orientation=tkinter_tix.HORIZONTAL)
    # box.add('ok', text='Ok', underline=0, command=w.destroy, width=6)
    box.add('exit', text='Exit', underline=0, command=w.destroy, width=6)