How to use the pydicom.multival.MultiValue 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 / tests / test_filewriter.py View on Github external
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
github pydicom / pydicom / tests / test_multival.py View on Github external
def testMultiDS(self):
        """MultiValue: Multi-valued data elements can be created........"""
        multival = MultiValue(DS, ['11.1', '22.2', '33.3'])
        for val in multival:
            self.assertTrue(isinstance(val, (DSfloat, DSdecimal)),
                            "Multi-value DS item not converted to DS")
github pydicom / pydicom / tests / test_multival.py View on Github external
def testSetIndex(self):
        """MultiValue: Setting list item converts it to required type"""
        multival = MultiValue(IS, [1, 5, 10])
        multival[1] = '7'
        self.assertTrue(isinstance(multival[1], IS))
        self.assertEqual(multival[1], 7, "Item set by index is not correct value")
github pydicom / pydicom / tests / test_multival.py View on Github external
def testIssue236DeepCopy(self):
        """MultiValue: deepcopy of MultiValue does not generate an error"""
        multival = MultiValue(IS, range(7))
        deepcopy(multival)
        multival = MultiValue(DS, range(7))
        deepcopy(multival)
        multival = MultiValue(DSfloat, range(7))
        deepcopy(multival)
github pydicom / pydicom / pydicom / values.py View on Github external
Returns
    -------
    str or list of str or valuerep.DT or list of DT
        if
        :attr:`~pydicom.config.datetime_conversion` is ``True`` then returns
        :class:`~pydicom.valuerep.DT` or a :class:`list` of ``DT``, otherwise
        returns :class:`str` or ``list`` of ``str``.
    """
    if config.datetime_conversion:
        if not in_py2:
            byte_string = byte_string.decode(default_encoding)
        splitup = byte_string.split("\\")
        if len(splitup) == 1:
            return _DT_from_byte_string(splitup[0])
        else:
            return MultiValue(_DT_from_byte_string, splitup)
    else:
        return convert_string(byte_string, is_little_endian, struct_format)
github pydicom / pydicom / pydicom / values.py View on Github external
encodings : list of str, optional
        A list of the character encoding schemes used to encode the value.

    Returns
    -------
    unicode or list of unicode
        The decoded value(s) if in Python 2.
    str or list of str
        The decoded value(s) if in Python 3.
    """
    values = byte_string.split(b'\\')
    values = [convert_single_string(value, encodings) for value in values]
    if len(values) == 1:
        return values[0]
    else:
        return MultiValue(compat.text_type, values)
github fastai / fastai_dev / dev / fastai2 / medical / imaging.py View on Github external
def _split_elem(res,k,v):
    if not isinstance(v,DcmMultiValue): return
    res[f'Multi{k}'] = 1
    for i,o in enumerate(v): res[f'{k}{"" if i==0 else i}']=o
github supervisely / supervisely / plugins / import / dicom / src / main.py View on Github external
def get_LUT_value(data, window, level, rescale_intercept=0, rescale_slope=1):
    if isinstance(window, list) or isinstance(window, MultiValue):
        window = window[0]
    if isinstance(level, list) or isinstance(level, MultiValue):
        level = int(level[0])

    # some vendors use wrong rescale intercept and slope?
    if rescale_slope == 0 and rescale_intercept == 1:
        rescale_slope = 1
        rescale_intercept = 0

    m_w = window - 1
    m_l = level - 0.5

    rescaled_data = (data * rescale_slope) + rescale_intercept
    cond_list = [rescaled_data <= (m_l - m_w / 2), rescaled_data > (m_l + m_w / 2)]
    func_list = [0, 255, lambda v: ((v - m_l) / m_w + 0.5) * (255 - 0)]
    return np.piecewise(rescaled_data, cond_list, func_list)
github girder / girder / plugins / dicom_viewer / girder_dicom_viewer / __init__.py View on Github external
float,
        six.binary_type,
        six.text_type,
        datetime.datetime,
        datetime.date,
        datetime.time,
    }:
        if isinstance(value, knownBaseType):
            return knownBaseType(value)

    # In Python3, pydicom does not treat the PersonName type as a subclass of a text type
    if isinstance(value, pydicom.valuerep.PersonName3):
        return value.encode('utf-8')

    # Handle lists (MultiValue) recursively
    if isinstance(value, pydicom.multival.MultiValue):
        if isinstance(value, pydicom.sequence.Sequence):
            # A pydicom Sequence is a nested list of Datasets, which is too complicated to flatten
            # now
            raise ValueError('Cannot coerce a Sequence')
        return list(map(_coerceValue, value))

    raise ValueError('Unknown type', type(value))
github ryanneph / PyMedImage / pymedimage / dcmio.py View on Github external
sets[l] = set()

    dcm_counter = 0
    for r, dirs, files in os.walk(root, topdown=True):
        # build the list of valid dicom file paths then load them after walk
        for file in files:
            _, file_extension = os.path.splitext(file)
            if file_extension in ['.dcm', '.dicom']:
                try:
                    ds = read_dicom(os.path.join(r, file))
                    dcm_counter += 1

                    for l, s in sets.items():
                        #print(l)
                        val = ds.get(l)
                        if isinstance(val, pydicom.multival.MultiValue):
                            val = tuple(val)
                        #print(type(val))
                        s.add(val)
                except:
                    continue

        if (not recursive):
            # clear dirs so that walk stops after this level
            del dirs[:]

    if not silent:
        print('Finished probing {:d} dicom files.'.format(dcm_counter))
        print('')
        print('Probe Results:')
        print('--------------')
        for l, s in sets.items():