Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
self.get_images()
image_files = [i.split(PathDicom)[1][1:] for i in self.dicom_names]
RT_Files = [os.path.join(PathDicom, file) for file in fileList if file not in image_files]
reader = sitk.ImageFileReader()
for lstRSFile in RT_Files:
reader.SetFileName(lstRSFile)
try:
reader.ReadImageInformation()
modality = reader.GetMetaData("0008|0060")
except:
modality = pydicom.read_file(lstRSFile).Modality
if modality.lower().find('dose') != -1:
self.RDs_in_case[lstRSFile] = []
elif modality.lower().find('struct') != -1:
self.RTs_in_case[lstRSFile] = []
self.RefDs = pydicom.read_file(self.dicom_names[0])
self.ds = pydicom.read_file(self.dicom_names[0])
self.all_contours_exist = False
self.rois_in_case = []
self.all_RTs.update(self.RTs_in_case)
if len(self.RTs_in_case.keys()) > 0:
self.template = False
for self.lstRSFile in self.RTs_in_case:
self.get_rois_from_RT()
elif self.get_images_mask:
self.use_template()
image_files = [i.split(PathDicom)[1][1:] for i in self.dicom_names]
RT_Files = [os.path.join(PathDicom, file) for file in fileList if file not in image_files]
reader = sitk.ImageFileReader()
for lstRSFile in RT_Files:
reader.SetFileName(lstRSFile)
try:
reader.ReadImageInformation()
modality = reader.GetMetaData("0008|0060")
except:
modality = pydicom.read_file(lstRSFile).Modality
if modality.lower().find('dose') != -1:
self.RDs_in_case[lstRSFile] = []
elif modality.lower().find('struct') != -1:
self.RTs_in_case[lstRSFile] = []
self.RefDs = pydicom.read_file(self.dicom_names[0])
self.ds = pydicom.read_file(self.dicom_names[0])
self.all_contours_exist = False
self.rois_in_case = []
self.all_RTs.update(self.RTs_in_case)
if len(self.RTs_in_case.keys()) > 0:
self.template = False
for self.lstRSFile in self.RTs_in_case:
self.get_rois_from_RT()
elif self.get_images_mask:
self.use_template()
def save_test_file(f, out_path, img_size):
img = pydicom.read_file(f).pixel_array
name = f.split('/')[-1][:-4]
img = resize(img,(img_size,img_size)) * 255
cv2.imwrite('{}/test/{}.png'.format(out_path, name), img)
def dcm2png_dir(in_dir, out_dir, desire_dim, desire_size, verbose=False):
mk_dir(out_dir)
data_path = os.path.join(out_dir, "ori_data.npy")
if os.path.exists(data_path):
pass
# return
slices = []
for s in os.listdir(in_dir):
if ".dcm" in s:
slices.append(pydicom.read_file(os.path.join(in_dir, s)))
slices.sort(key=lambda x: int(x.InstanceNumber))
image = get_pixels_hu(slices)
pixel_spacing = slices[0].PixelSpacing
pixel_spacing.append(slices[0].SliceThickness)
image = rescale_images(image, pixel_spacing, 1.5, verbose=verbose)
# image = resize_np(image, desire_dim, desire_size, verbose=verbose)
image = normalize_hu(image)
# print(image.dtype, image.max(), image.min()) #should be float32 between [0.0, 1.0]
np.save(data_path, image)
def use_template(self):
self.template = True
if not self.template_dir:
self.template_dir = os.path.join('\\\\mymdafiles', 'ro-admin', 'SHARED', 'Radiation physics', 'BMAnderson',
'Auto_Contour_Sites', 'template_RS.dcm')
if not os.path.exists(self.template_dir):
self.template_dir = os.path.join('..', '..', 'Shared_Drive', 'Auto_Contour_Sites', 'template_RS.dcm')
self.key_list = self.template_dir.replace('template_RS.dcm', 'key_list.txt')
self.RS_struct = pydicom.read_file(self.template_dir)
print('Running off a template')
self.changetemplate()
def beam_complexity(cnx, study_instance_uid):
rt_plan_query = cnx.query('DICOM_Files', 'folder_path, plan_file',
"study_instance_uid = '%s'" % study_instance_uid)[0]
rt_plan_file_path = join_path(rt_plan_query[0], rt_plan_query[1])
rt_plan = dicom.read_file(rt_plan_file_path)
for beam_num, beam in enumerate(rt_plan.BeamSequence):
try:
condition = "study_instance_uid = '%s' and beam_number = '%s'" % (study_instance_uid, (beam_num + 1))
meterset = float(cnx.query('Beams', 'beam_mu', condition)[0][0])
mlca_data = mlca(beam, meterset, ignore_zero_mu_cp=True)
mlc_keys = ['area', 'x_perim', 'y_perim', 'cmp_score', 'cp_mu']
summary_stats = {key: calc_stats(mlca_data.summary[key]) for key in mlc_keys}
column_vars = {'area': 'area', 'x_perim': 'x_perim', 'y_perim': 'y_perim', 'complexity': 'cmp_score',
'cp_mu': 'cp_mu'}
stat_map = {'min': 5, 'mean': 3, 'median': 2, 'max': 0}
for c in list(column_vars):
for s in list(stat_map):
value = summary_stats[column_vars[c]][stat_map[s]]
plan_files.append(f[x])
study_uid_plan.append(dicom_file.StudyInstanceUID)
elif dicom_file.Modality.lower() == 'rtstruct':
structure_files.append(f[x])
study_uid_structure.append(dicom_file.StudyInstanceUID)
elif dicom_file.Modality.lower() == 'rtdose':
dose_files.append(f[x])
study_uid_dose.append(dicom_file.StudyInstanceUID)
except Exception:
pass
self.count = len(plan_files)
for a in range(self.count):
self.plan.append(plan_files[a])
self.mrn.append(dicom.read_file(plan_files[a]).PatientID)
self.study_instance_uid.append(dicom.read_file(plan_files[a]).StudyInstanceUID)
for b in range(len(structure_files)):
if study_uid_plan[a] == study_uid_structure[b]:
self.structure.append(structure_files[b])
for c in range(len(dose_files)):
if study_uid_plan[a] == study_uid_dose[c]:
self.dose.append(dose_files[c])
if self.count == 0:
self.plan.append('')
self.mrn.append('')
self.structure.append('')
self.dose.append('')
def load_dcm(folder):
slices = []
for s in os.listdir(folder):
if ".dcm" in s:
slices.append(pydicom.read_file(os.path.join(folder, s)))
slices.sort(key=lambda x: int(x.InstanceNumber))
data = get_pixels_hu(slices)
return data
def __validate_input(rt_dose):
"""Ensure provided input is either an RT Dose pydicom.FileDataset or a file_path to one"""
if type(rt_dose) is pydicom.FileDataset:
if rt_dose.Modality.lower() == 'rtdose':
return rt_dose
msg = "DoseGrid.__validate_input: The provided pydicom.FileDataset is not RTDOSE"
push_to_log(msg=msg)
return
elif isfile(rt_dose):
try:
rt_dose_ds = pydicom.read_file(rt_dose)
if rt_dose_ds.Modality.lower() == 'rtdose':
return rt_dose_ds
msg = 'DoseGrid.__validate_input: ' \
'The provided file_path points to a DICOM file, but it is not an RT Dose file.'
push_to_log(msg=msg)
except Exception as e:
msg = 'DoseGrid.__validate_input: ' \
'The provided input is neither a pydicom.FileDataset nor could it be read by pydicom.'
push_to_log(e, msg=msg)
return
def get_rois_from_RT(self):
rois_in_structure = []
self.RS_struct = pydicom.read_file(self.lstRSFile)
if Tag((0x3006, 0x020)) in self.RS_struct.keys():
self.ROI_Structure = self.RS_struct.StructureSetROISequence
else:
self.ROI_Structure = []
for Structures in self.ROI_Structure:
if Structures.ROIName not in self.rois_in_case:
self.rois_in_case.append(Structures.ROIName)
rois_in_structure.append(Structures.ROIName)
self.all_RTs[self.lstRSFile] = rois_in_structure