Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
preamble : str/bytes or None
The 128-byte DICOM preamble will be returned if the appropriate prefix
('DICM') is found at byte offset 128. Returns ``None`` if the 'DICM'
prefix is not found and `force` is ``True``.
Raises
------
InvalidDicomError
If `force` is ``False`` and no appropriate header information found.
Notes
-----
Also reads past the 'DICM' marker. Rewinds file to the beginning if
no header found.
"""
logger.debug("Reading File Meta Information preamble...")
preamble = fp.read(128)
if config.debugging:
sample = bytes2hex(preamble[:8]) + "..." + bytes2hex(preamble[-8:])
logger.debug("{0:08x}: {1}".format(fp.tell() - 128, sample))
logger.debug("Reading File Meta Information prefix...")
magic = fp.read(4)
if magic != b"DICM" and force:
logger.info(
"File is not conformant with the DICOM File Format: 'DICM' "
"prefix is missing from the File Meta Information header "
"or the header itself is missing. Assuming no header and "
"continuing.")
preamble = None
fp.seek(0)
elif magic != b"DICM" and not force:
'Dataset elements.')
# OK if is subclass, e.g. DeferredDataElement
if not isinstance(value, (DataElement, RawDataElement)):
raise TypeError("Dataset contents must be DataElement instances.")
if isinstance(value.tag, BaseTag):
tag = value.tag
else:
tag = Tag(value.tag)
if key != tag:
raise ValueError("DataElement.tag must match the dictionary key")
data_element = value
if tag.is_private:
# See PS 3.5-2008 section 7.8.1 (p. 44) for how blocks are reserved
logger.debug("Setting private tag %r" % tag)
private_block = tag.elem >> 8
private_creator_tag = Tag(tag.group, private_block)
if private_creator_tag in self and tag != private_creator_tag:
if data_element.is_raw:
data_element = DataElement_from_raw(
data_element, self._character_set)
data_element.private_creator = self[private_creator_tag].value
self._dict[tag] = data_element
# Package names
names = [hh_deps[name][1] for name in missing]
pkg_msg.append(
"{} (req. {})"
.format(hh.HANDLER_NAME, ', '.join(names))
)
raise RuntimeError(msg + ', '.join(pkg_msg))
last_exception = None
for handler in available_handlers:
try:
self._do_pixel_data_conversion(handler)
return
except Exception as exc:
logger.debug(
"Exception raised by pixel data handler", exc_info=exc
)
last_exception = exc
# The only way to get to this point is if we failed to get the pixel
# array because all suitable handlers raised exceptions
self._pixel_array = None
self._pixel_id = None
logger.info(
"Unable to decode the pixel data using the following handlers: {}."
"Please see the list of supported Transfer Syntaxes in the "
"pydicom documentation for alternative packages that might "
"be able to decode the data"
.format(", ".join([str(hh) for hh in available_handlers]))
)
>>> 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:
logger.debug("Caller passed file object")
else:
logger.debug("Caller passed file name")
logger.debug("-" * 80)
# Convert size to defer reading into bytes
defer_size = size_in_bytes(defer_size)
# Iterate through all items and store them --include file meta if present
stop_when = None
if stop_before_pixels:
logger.debug("Reading File Meta Information prefix...")
magic = fp.read(4)
if magic != b"DICM" and force:
logger.info(
"File is not conformant with the DICOM File Format: 'DICM' "
"prefix is missing from the File Meta Information header "
"or the header itself is missing. Assuming no header and "
"continuing.")
preamble = None
fp.seek(0)
elif magic != b"DICM" and not force:
raise InvalidDicomError("File is missing DICOM File Meta Information "
"header or the 'DICM' prefix is missing from "
"the header. Use force=True to force reading.")
else:
logger.debug("{0:08x}: 'DICM' prefix found".format(fp.tell() - 4))
return preamble
------
InvalidDicomError
If `force` is ``False`` and no appropriate header information found.
Notes
-----
Also reads past the 'DICM' marker. Rewinds file to the beginning if
no header found.
"""
logger.debug("Reading File Meta Information preamble...")
preamble = fp.read(128)
if config.debugging:
sample = bytes2hex(preamble[:8]) + "..." + bytes2hex(preamble[-8:])
logger.debug("{0:08x}: {1}".format(fp.tell() - 128, sample))
logger.debug("Reading File Meta Information prefix...")
magic = fp.read(4)
if magic != b"DICM" and force:
logger.info(
"File is not conformant with the DICOM File Format: 'DICM' "
"prefix is missing from the File Meta Information header "
"or the header itself is missing. Assuming no header and "
"continuing.")
preamble = None
fp.seek(0)
elif magic != b"DICM" and not force:
raise InvalidDicomError("File is missing DICOM File Meta Information "
"header or the 'DICM' prefix is missing from "
"the header. Use force=True to force reading.")
else:
logger.debug("{0:08x}: 'DICM' prefix found".format(fp.tell() - 4))
return preamble
Returns
-------
str
If the element is in the DICOM data dictionary then returns the
corresponding element's keyword, otherwise returns ``''``. For
group length elements will always return ``'GroupLength'``.
"""
try:
return dictionary_keyword(tag)
except KeyError:
return ""
# Provide for the 'reverse' lookup. Given the keyword, what is the tag?
logger.debug("Reversing DICOM dictionary so can look up tag from a keyword...")
keyword_dict = dict([(dictionary_keyword(tag), tag)
for tag in DicomDictionary])
def tag_for_keyword(keyword):
"""Return the tag of the element corresponding to `keyword`.
Only performs the lookup for official DICOM elements.
Parameters
----------
keyword : str
The keyword for the element whose tag is being retrieved.
Returns
-------
group, elem, length = unpack(struct_format, fp.read(8))
tag = TupleTag((group, elem))
if tag != delimiter:
msg = ("Did not find expected delimiter '%s'" %
dictionary_description(delimiter))
msg += ", instead found %s at file position 0x%x" % (
str(tag), fp.tell() - 8)
logger.warn(msg)
fp.seek(fp.tell() - 8)
return
logger.debug("%04x: Found Delimiter '%s'", fp.tell() - 8,
dictionary_description(delimiter))
if length == 0:
logger.debug("%04x: Read 0 bytes after delimiter", fp.tell() - 4)
else:
logger.debug("%04x: Expected 0x00000000 after delimiter, found 0x%x",
fp.tell() - 4, length)
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:
logger.debug("Caller passed file object")
else:
logger.debug("Caller passed file name")
logger.debug("-" * 80)
# Convert size to defer reading into bytes
defer_size = size_in_bytes(defer_size)
# Iterate through all items and store them --include file meta if present
stop_when = None
if stop_before_pixels:
stop_when = _at_pixel_data
try:
dataset = read_partial(fp, stop_when, defer_size=defer_size,
force=force, specific_tags=specific_tags)
finally:
if not caller_owns_file:
Returns
-------
dataelem.RawDataElement
The data element with the value set.
Raises
------
IOError
If `filename_or_obj` is ``None``.
IOError
If `filename_or_obj` is a filename and the corresponding file does
not exist.
ValueError
If the VR or tag of `raw_data_elem` does not match the read value.
"""
logger.debug("Reading deferred element %r" % str(raw_data_elem.tag))
# If it wasn't read from a file, then return an error
if filename_or_obj is None:
raise IOError("Deferred read -- original filename not stored. "
"Cannot re-open")
is_filename = isinstance(filename_or_obj, compat.string_types)
# Check that the file is the same as when originally read
if is_filename and not os.path.exists(filename_or_obj):
raise IOError(u"Deferred read -- original file "
"{0:s} is missing".format(filename_or_obj))
if timestamp is not None:
statinfo = os.stat(filename_or_obj)
if statinfo.st_mtime != timestamp:
warnings.warn("Deferred read warning -- file modification time "
"has changed.")