Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
Parameters
----------
elem : pydicom.dataelem.DataElement
The element to encode
is_implicit_VR : bool
Encode using implicit VR, default True
is_little_endian : bool
Encode using little endian, default True
Returns
-------
str or bytes
The encoded element as str (python2) or bytes (python3)
"""
with DicomBytesIO() as fp:
fp.is_implicit_VR = is_implicit_VR
fp.is_little_endian = is_little_endian
write_data_element(fp, elem)
return fp.parent.getvalue()
def compare_logfile_within_zip(zip_filepath):
with open(zip_filepath, 'rb') as input_file:
data = io.BytesIO(input_file.read())
data_zip = zipfile.ZipFile(data)
namelist = data_zip.namelist()
dicom_files = [path for path in namelist if path.endswith('.dcm')]
assert len(dicom_files) == 1
dicom_file = dicom_files[0]
with data_zip.open(dicom_file) as file_object:
dcm_bytes = DicomBytesIO(file_object.read())
dcm = pydicom.dcmread(dcm_bytes)
MUDensity.from_dicom(dcm)
def setUp(self):
# Create a dummy (in memory) file to write to
self.f1 = DicomBytesIO()
self.f1.is_little_endian = True
self.f1.is_implicit_VR = True
def setUp(self):
"""Create an empty file-like for use in testing."""
self.fp = DicomBytesIO()
self.fp.is_little_endian = True
self.fp.is_implicit_VR = True
def test_equal():
dicom1 = DicomBase.from_dict(
{"Manufacturer": "PyMedPhys", "PatientName": "Python^Monte"}
)
dicom2 = DicomBase.from_dict(
{"Manufacturer": "PyMedPhys", "PatientName": "Python^Monte"}
)
assert dicom1 == dicom2 # Equality from dict
try:
fp1 = pydicom.filebase.DicomBytesIO()
dicom1.to_file(fp1)
fp2 = pydicom.filebase.DicomBytesIO()
dicom2.to_file(fp2)
dicom1_from_file = DicomBase.from_file(fp1)
dicom2_from_file = DicomBase.from_file(fp2)
# Equality from file (implicitly also from dataset)
assert dicom1_from_file == dicom2_from_file
dicom1_from_file.dataset.PatientName = "test^PatientName change"
assert dicom1_from_file != dicom2_from_file # Negative case
dicom1_from_file.dataset.PatientName = "Python^Monte"
assert dicom1_from_file == dicom2_from_file # Equality post re-assignment
dicom1_from_file_copied = deepcopy(dicom1_from_file)
assert dicom1_from_file == dicom1_from_file_copied # Equality from deepcopy
finally:
def convert_dicom_to_jpg(name):
try:
data = f.read(name)
dirtype = 'train' if 'train' in name else 'test'
imgnm = (name.split('/')[-1]).replace('.dcm', '')
dicom = pydicom.dcmread(DicomBytesIO(data))
image = dicom.pixel_array
image = rescale_image(image, rescaledict['RescaleSlope'][imgnm], rescaledict['RescaleIntercept'][imgnm])
image = apply_window_policy(image)
image -= image.min((0,1))
image = (255*image).astype(np.uint8)
cv2.imwrite(os.path.join(path_proc, dirtype, imgnm)+'.jpg', image)
except:
print(name)
The dataset to encode
is_implicit_vr : bool
The element encoding scheme the dataset will be encoded with, ``True``
for implicit VR, ``False`` for explicit VR.
is_little_endian : bool
The byte ordering the dataset will be encoded in, ``True`` for little
endian, ``False`` for big endian.
Returns
-------
bytes or None
The encoded dataset as :class:`bytes` (if successful) or ``None`` if
the encoding failed.
"""
# pylint: disable=broad-except
fp = DicomBytesIO()
fp.is_implicit_VR = is_implicit_vr
fp.is_little_endian = is_little_endian
try:
write_dataset(fp, ds)
except Exception as ex:
LOGGER.error("pydicom.write_dataset() failed:")
LOGGER.error(ex)
fp.close()
return None
bytestring = fp.parent.getvalue()
fp.close()
return bytestring
def encode_element(elem, is_implicit_VR, is_little_endian):
"""Encode a pydicom DataElement to a byte stream."""
fp = DicomBytesIO()
fp.is_implicit_VR = is_implicit_VR
fp.is_little_endian = is_little_endian
write_data_element(fp, elem)
rawstr = fp.parent.getvalue()
fp.close()
return rawstr
def write_data_element(fp, data_element, encodings=None):
"""Write the data_element to file fp according to
dicom media storage rules.
"""
# Write element's tag
fp.write_tag(data_element.tag)
# write into a buffer to avoid seeking back which can be expansive
buffer = DicomBytesIO()
buffer.is_little_endian = fp.is_little_endian
buffer.is_implicit_VR = fp.is_implicit_VR
VR = data_element.VR
if not fp.is_implicit_VR and len(VR) != 2:
msg = ("Cannot write ambiguous VR of '{}' for data element with "
"tag {}.\nSet the correct VR before writing, or use an "
"implicit VR transfer syntax".format(
VR, repr(data_element.tag)))
raise ValueError(msg)
if data_element.is_raw:
# raw data element values can be written as they are
buffer.write(data_element.value)
is_undefined_length = data_element.length == 0xFFFFFFFF
else:
If `enforce_standard` is ``True`` and any of the required *File Meta
Information* elements are missing from `file_meta`, with the
exception of (0002,0000), (0002,0001) and (0002,0012).
ValueError
If any non-Group 2 Elements are present in `file_meta`.
"""
validate_file_meta(file_meta, enforce_standard)
if enforce_standard and 'FileMetaInformationGroupLength' not in file_meta:
# Will be updated with the actual length later
file_meta.FileMetaInformationGroupLength = 0
# Write the File Meta Information Group elements
# first write into a buffer to avoid seeking back, that can be
# expansive and is not allowed if writing into a zip file
buffer = DicomBytesIO()
buffer.is_little_endian = True
buffer.is_implicit_VR = False
write_dataset(buffer, file_meta)
# If FileMetaInformationGroupLength is present it will be the first written
# element and we must update its value to the correct length.
if 'FileMetaInformationGroupLength' in file_meta:
# Update the FileMetaInformationGroupLength value, which is the number
# of bytes from the end of the FileMetaInformationGroupLength element
# to the end of all the File Meta Information elements.
# FileMetaInformationGroupLength has a VR of 'UL' and so has a value
# that is 4 bytes fixed. The total length of when encoded as
# Explicit VR must therefore be 12 bytes.
file_meta.FileMetaInformationGroupLength = buffer.tell() - 12
buffer.seek(0)
write_data_element(buffer, file_meta[0x00020000])