コード例 #1
0
def create_RT_On_Primary(path):
    Dicom_reader = Dicom_to_Imagestack(get_images_mask=True)
    for MRN in os.listdir(path):
        MRN_path = os.path.join(path, MRN)
        data_dict = {'Path': [], 'Images': [], 'Vals': []}
        exams = []
        for _, exams, _ in os.walk(MRN_path):
            break
        for exam in exams:
            exam_path = os.path.join(MRN_path, exam)
            Dicom_reader.make_array(exam_path)
            Images = Dicom_reader.ArrayDicom
            non_min = np.where(Images > np.min(Images))
            if non_min:
                data_dict['Images'].append(Images)
                data_dict['Vals'].append(len(non_min[0]))
                data_dict['Path'].append(exam_path)
        primary = data_dict['Vals'].index(np.max(data_dict['Vals']))
        out_RT = np.zeros(data_dict['Images'][primary].shape)
        out_RT = np.expand_dims(out_RT, axis=-1)
        out_RT = np.repeat(out_RT, repeats=len(data_dict['Vals']), axis=-1)
        cast_index = 1
        for index in range(len(data_dict['Vals'])):
            if index == primary:
                continue
            Images = data_dict['Images'][index]
            output = np.zeros(Images.shape)
            output[Images > np.min(Images)] = 1
            out_RT[..., cast_index] = output
コード例 #2
0
def print_rois_curate(base_path, check_rois=None):
    associations = return_association_dict()
    k = Dicom_to_Imagestack(get_images_mask=False,
                            associations=associations,
                            Contour_Names=check_rois)
    k.down_folder(base_path)
    for roi in k.all_rois:
        print(roi)
    print('Make an associations file form these roi lists')
 def __init__(self):
     self.Fill_Missing_Segments_Class = Fill_Missing_Segments()
     self.Contour_Names = ['Liver'] + [
         'Liver_Segment_{}'.format(i) for i in range(1, 9)
     ]
     self.Out_Contour_names = [
         'Liver_Segment_fixed_{}'.format(i) for i in range(1, 9)
     ]
     self.Dicom_Reader = Dicom_to_Imagestack(
         arg_max=False,
         Contour_Names=self.Contour_Names,
         delete_previous_rois=True)
コード例 #4
0
class Niftii_To_Annotation(object):
    def __init__(self, ROI_Names=None):
        self.ROI_Names = ROI_Names
        self.Dicom_reader = Dicom_to_Imagestack()

    def niftii_to_annotation(self, dicom_path, nifti_annotation_path,
                             out_path):
        self.Dicom_reader.make_array(dicom_path)
        annotations = sitk.ReadImage(nifti_annotation_path)
        annotations = sitk.GetArrayFromImage(annotations)
        annotations = to_categorical(annotations)
        # annotations[..., 1] += annotations[..., 2]
        self.Dicom_reader.with_annotations(annotations,
                                           out_path,
                                           ROI_Names=self.ROI_Names)
コード例 #5
0
def convert_rts(base_path):
    for path, directories, files in os.walk(
            base_path):  # Look through all folders
        files = [i for i in files
                 if i.endswith('.dcm')]  # Stop if we have something with dicom
        if files and len(
                files
        ) > 5 and 'New_RT' not in directories:  # Only go forward if we have at least 5 images
            base_reader = Dicom_to_Imagestack(
                get_images_mask=False
            )  # Make a base reader to identify the contour names
            base_reader.down_folder(path)
            contour_names = base_reader.rois_in_case  # Keep the same nomenclature for naming
            if not contour_names:
                print('No contours found at {}'.format(path))
                continue
            reader = Dicom_to_Imagestack(
                get_images_mask=True,
                Contour_Names=contour_names,
                arg_max=False
            )  # Now, create a new reader to create a mask of the contours
            reader.Make_Contour_From_directory(
                path)  # Create the images and mask from the path
            reader.use_template(
            )  # Shift over to our template for re-writing them
            reader.with_annotations(
                reader.mask,
                output_dir=os.path.join(path, 'New_RT'),
                ROI_Names=contour_names)  # Write the new RT structure out
class Fix_Missing_Segments_Class(object):
    def __init__(self):
        self.Fill_Missing_Segments_Class = Fill_Missing_Segments()
        self.Contour_Names = ['Liver'] + [
            'Liver_Segment_{}'.format(i) for i in range(1, 9)
        ]
        self.Out_Contour_names = [
            'Liver_Segment_fixed_{}'.format(i) for i in range(1, 9)
        ]
        self.Dicom_Reader = Dicom_to_Imagestack(
            arg_max=False,
            Contour_Names=self.Contour_Names,
            delete_previous_rois=True)

    def run_on_path(self, path):
        self.path = path
        self.Dicom_Reader.Make_Contour_From_directory(self.path)

    def write_output_as_RT(self, annotations=None):
        if annotations is None:
            annotations = self.final_annotations
        self.Dicom_Reader.with_annotations(annotations,
                                           os.path.join(self.path, 'new_RS'),
                                           ROI_Names=self.Out_Contour_names)

    def iterate_mask(self):
        try:
            ground_truth = self.Dicom_Reader.mask[..., 1]
        except:
            return None
        annotations = self.Dicom_Reader.mask[..., (0, 2, 3, 4, 5, 6, 7, 8, 9)]
        overlap = np.sum(annotations, axis=-1)
        annotations[overlap > 1] = 0
        self.final_annotations = self.Fill_Missing_Segments_Class.iterate_annotations(
            annotations,
            ground_truth,
            spacing=self.Dicom_Reader.annotation_handle.GetSpacing())
        # annotations[ground_truth==0] = 0
        # spacing = self.Dicom_Reader.annotation_handle.GetSpacing()
        # re_organized_spacing = spacing[-1::-1]
        # differences = [0,np.inf]
        # index = 0
        # while np.abs(differences[-1] - differences[-2]) > 50 and index < 15:
        #     index += 1
        #     print('Iterating {}'.format(index))
        #     previous_iteration = copy.deepcopy(np.argmax(annotations,axis=-1))
        #     annotations = remove_56_78(annotations)
        #     for i in range(1, annotations.shape[-1]):
        #         annotations[..., i] = remove_non_liver(annotations[..., i], do_3D=False, do_2D=True,min_area=10,spacing=re_organized_spacing)
        #     spacing = self.Dicom_Reader.annotation_handle.GetSpacing()
        #     annotations = self.Fill_Missing_Segments_Class.make_distance_map(annotations, ground_truth,spacing=spacing)
        #     differences.append(np.abs(np.sum(previous_iteration[ground_truth==1]-np.argmax(annotations,axis=-1)[ground_truth==1])))
        # self.final_annotations = annotations

    def write_output_as_nifti(self, out_path, images_desc, iteration):
        new_annotations = sitk.GetImageFromArray(
            np.argmax(self.final_annotations, axis=-1).astype('int8'))
        new_annotations.SetSpacing(self.Dicom_Reader.dicom_handle.GetSpacing())
        new_annotations.SetOrigin(self.Dicom_Reader.dicom_handle.GetOrigin())
        new_annotations.SetDirection(
            self.Dicom_Reader.dicom_handle.GetDirection())
        if not os.path.exists(out_path):
            os.makedirs(out_path)
        image_path = os.path.join(
            out_path,
            'Overall_Data_' + images_desc + '_' + str(iteration) + '.nii.gz')
        sitk.WriteImage(self.Dicom_Reader.dicom_handle, image_path)
        annotation_path = os.path.join(
            out_path,
            'Overall_mask_' + images_desc + '_y' + str(iteration) + '.nii.gz')
        sitk.WriteImage(new_annotations, annotation_path)
コード例 #7
0
excel_file = os.path.join('..', 'Data',
                          'Post_treatment_and_Recurrence_info.xlsx')
output_file = os.path.join('..', 'Data',
                           'Post_treatment_and_Recurrence_info_output.xlsx')
status_path = os.path.join('..', 'Data', 'Status')
if not os.path.exists(status_path):
    os.makedirs(status_path)
data = pd.read_excel(excel_file)
MRNs = [data['MRN'].array[-1]]
for MRN in MRNs:
    index = list(data['MRN'].array).index(MRN)
    MRN = str(data['MRN'][index])
    print(MRN)
    Recurrence = data['Recurrence'][index]
    recurrence_path = os.path.join(images_path, MRN, Recurrence)
    recurrence_reader = Dicom_to_Imagestack(
        arg_max=False, Contour_Names=['Test_Ablation', 'Test_Cross'])
    recurrence_reader.Make_Contour_From_directory(recurrence_path)

    mask = recurrence_reader.mask
    ablation_base = mask[..., 1]
    cross_base = mask[..., 2]

    centroid_of_ablation_recurrence = np.asarray(center_of_mass(ablation_base))
    spacing = recurrence_reader.annotation_handle.GetSpacing()
    output = create_output_ray(centroid_of_ablation_recurrence,
                               spacing=spacing,
                               ref_binary_image=cross_base,
                               margin_rad=np.deg2rad(2),
                               margin=50,
                               min_max=False)
    recurrence_reader.with_annotations(output,
コード例 #8
0
 def __init__(self, ROI_Names=None):
     self.ROI_Names = ROI_Names
     self.Dicom_reader = Dicom_to_Imagestack()
コード例 #9
0
        out_file = os.path.join(patient_data_path,
                                desc + '_Iteration_' + str(iteration) + '.txt')
        if not os.path.exists(out_file):
            Dicom_Reader.Make_Contour_From_directory(patient_data_path)
            Dicom_Reader.set_iteration(iteration)
            Dicom_Reader.write_images_annotations(out_path)
        iteration += 1
    return None


associations = {
    'Liver_BMA_Program_4': 'Liver',
    'bma_liver': 'Liver',
    'best_liver': 'Liver',
    'tried_liver': 'Liver'
}
data_path = os.path.join('..', 'Data', 'Whole_Patients')
output_path = os.path.join('..', 'Data', 'Niftii_Arrays')
Dicom_Reader = Dicom_to_Imagestack(get_images_mask=False)
# Dicom_Reader.down_folder(data_path)
# all_rois = Dicom_Reader.all_rois
Dicom_Reader.set_associations(associations)
Dicom_Reader.set_get_images_and_mask(True)
Dicom_Reader.set_contour_names(['Liver'])
Dicom_Reader.Make_Contour_From_directory(
    os.path.join(data_path, 'ABD_LYMPH_036'))

xxx = 1
# write_data(data_path,output_path, Dicom_Reader)
# Separate_files(output_path)
run_main(output_path, extension=5)