Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_require_patient_orientation_be_HFS():
test_ds_dict = {
key: pydicom.dcmread(get_data_file(key)) for key in ORIENTATIONS_SUPPORTED
}
ds_no_orient = pydicom.dcmread(
pjoin(dirname(DATA_DIRECTORY), "struct", "example_structures.dcm"), force=True
)
test_ds_dict["no orient"] = ds_no_orient
for orient, ds in test_ds_dict.items():
if orient == "HFS":
require_patient_orientation_be_HFS(ds)
elif orient == "no orient":
with pytest.raises(AttributeError) as ea:
require_patient_orientation_be_HFS(ds)
assert "object has no attribute 'ImageOrientationPatient'" in str(ea.value)
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(PATHPROC, dirtype, imgnm)+'.jpg', image)
except:
logger.info(name)
def load_image(full_path):
f = pydicom.dcmread(full_path)
return f.pixel_array.astype(np.int)
def read_dicom(filenm, ioptn):
dataset = pydicom.dcmread(filenm)
now = datetime.now()
ArrayDicom = np.zeros(
(dataset.Rows, dataset.Columns), dtype=dataset.pixel_array.dtype
)
ArrayDicom = dataset.pixel_array
SID = dataset.RTImageSID
print("array_shape=", np.shape(ArrayDicom))
height = np.shape(ArrayDicom)[0]
width = np.shape(ArrayDicom)[1]
dx = 1 / (SID * (1 / dataset.ImagePlanePixelSpacing[0]) / 1000)
dy = 1 / (SID * (1 / dataset.ImagePlanePixelSpacing[1]) / 1000)
print("pixel spacing row [mm]=", dx)
print("pixel spacing col [mm]=", dy)
# creating the figure extent based on the image dimensions, we divide by 10 to get the units in cm
def inspect_sourcefile(self, row: int=None, column: int=None):
"""When double clicked, show popup window. """
if row == 1 and column == 1:
sourcefile = Path(self.target_run['provenance'])
if bids.is_dicomfile(sourcefile):
sourcedata = pydicom.dcmread(str(sourcefile), force=True)
elif bids.is_parfile(sourcefile):
with open(sourcefile, 'r') as parfid:
sourcedata = parfid.read()
else:
LOGGER.warning(f"Could not read {self.dataformat} file: {sourcefile}")
return
self.popup = InspectWindow(sourcefile, sourcedata, self.dataformat)
self.popup.show()
self.popup.scrollbar.setValue(0) # This can only be done after self.popup.show()
def _parseFile(f):
try:
# download file and try to parse dicom
with File().open(f) as fp:
dataset = pydicom.dcmread(
fp,
# don't read huge fields, esp. if this isn't even really dicom
defer_size=1024,
# don't read image data, just metadata
stop_before_pixels=True)
return _coerceMetadata(dataset)
except pydicom.errors.InvalidDicomError:
# if this error occurs, probably not a dicom file
return None
def setup(self):
"""Setup the tests."""
self.no_runs = 100
self.ds_1_1_1 = dcmread(EXPL_1_1_1F)
self.ds_1_1_3 = dcmread(EXPL_1_1_3F)
self.ds_8_1_1 = dcmread(EXPL_8_1_1F)
self.ds_8_1_2 = dcmread(EXPL_8_1_2F)
self.ds_8_3_1 = dcmread(EXPL_8_3_1F)
self.ds_8_3_2 = dcmread(EXPL_8_3_2F)
self.ds_16_1_1 = dcmread(EXPL_16_1_1F)
self.ds_16_1_10 = dcmread(EXPL_16_1_10F)
self.ds_16_3_1 = dcmread(EXPL_16_3_1F)
self.ds_16_3_2 = dcmread(EXPL_16_3_2F)
self.ds_32_1_1 = dcmread(IMPL_32_1_1F)
self.ds_32_1_15 = dcmread(IMPL_32_1_15F)
self.ds_32_3_1 = dcmread(EXPL_32_3_1F)
self.ds_32_3_2 = dcmread(EXPL_32_3_2F)
self.ds_ybr_422 = dcmread(EXPL_8_3_1F_YBR422)
def is_CT_slice(file: str) -> bool:
"""Test if the file is a CT Image storage DICOM file."""
try:
ds = pydicom.dcmread(file, force=True, stop_before_pixels=True)
return ds.SOPClassUID.name == 'CT Image Storage'
except (InvalidDicomError, AttributeError, MemoryError):
return False
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
# print the image information given in the dataset
print('The information of the data set after downsampling: \n')