Beispiel #1
0
def contours2images(patient_folder):
    image_folder = pjoin(patient_folder, 'sa', 'images')
    con_file = pjoin(patient_folder, 'sa', 'contours.con')
    # reading the dicom files
    dr = DCMreaderVM(image_folder)

    # reading the contours
    cr = CONreaderVM(con_file)
    contours = cr.get_hierarchical_contours()

    # drawing the contours for the images
    for slc in contours:
        for frm in contours[slc]:
            image = dr.get_image(slc, frm)  # numpy array
            cntrs = []
            rgbs = []
            for mode in contours[slc][frm]:
                # choose color
                if mode == 'ln':  # left endocardium -> red
                    rgb = [1, 0, 0]
                elif mode == 'lp':  # left epicardium -> green
                    rgb = [0, 1, 0]
                elif mode == 'rn':  # right endocardium -> yellow
                    rgb = [1, 1, 0]
                else:
                    rgb = None
                if rgb is not None:
                    cntrs.append(contours[slc][frm][mode])
                    rgbs.append(rgb)
            if len(cntrs) > 0:
                draw(image, cntrs, rgbs)
Beispiel #2
0
def create_pickle_for_patient(in_dir, out_dir):
    scan_id = os.path.basename(in_dir)
    image_folder = os.path.join(in_dir, "sa", "images")
    con_file = os.path.join(in_dir, "sa", "contours.con")
    meta_txt = os.path.join(in_dir, "meta.txt")

    if not os.path.isdir(image_folder):
        logger.error("Could not find image folder for: {}".format(scan_id))
        return
    if not os.path.isfile(con_file):
        logger.error("Could not find .con file for: {}".format(scan_id))
        return
    if not os.path.isfile(meta_txt):
        logger.error("Could not find meta.txt file for: {}".format(scan_id))
        return

    dr = DCMreaderVM(image_folder)
    if dr.num_frames == 0 and dr.num_frames == 0 or dr.broken:
        logger.error("Could not create pickle file for {}".format(scan_id))
        return

    cr = CONreaderVM(con_file)
    contours = left_ventricle_contours(cr.get_hierarchical_contours())

    frame_slice_dict = collect_contour_slices_by_frames(contours)
    if not (len(frame_slice_dict) == 2):
        logger.error("Too many contour frames for {}".format(scan_id))
        return

    pickle_file_path = os.path.join(out_dir, scan_id + ".p")
    create_path_for_file(pickle_file_path)

    diastole_frame = frame_of_diastole(frame_slice_dict, contours)
    sampling_slices = calculate_sampling_slices(frame_slice_dict,
                                                diastole_frame)
    sampling_contours = []
    for slice_index in sampling_slices:
        shape = dr.get_image(slice_index, diastole_frame).shape
        sampling_contours.append(contours[slice_index][diastole_frame])
    pathology = read_pathology(meta_txt)
    shape = dr.get_image(sampling_slices[0], diastole_frame).shape
    contour_diff_matricies = create_contour_diff_matricies(
        sampling_contours, shape)
    print(type(contour_diff_matricies))
    patient_data = PatientData(scan_id, pathology, cr.get_volume_data(),
                               contour_diff_matricies)

    with (open(pickle_file_path, "wb")) as pickleFile:
        pickle.dump(patient_data, pickleFile)
Beispiel #3
0
def generate_patient_dataset(patient_id, patient_path, axis):
    axes = [
        d for d in os.listdir(patient_path)
        if os.path.isdir(pjoin(patient_path, d))
    ]
    if axis not in axes:
        logger.warning(f'Patient {patient_id} has no data for {axis}')
        return None

    axis_path = pjoin(patient_path, axis)
    if axis == 'sa':
        images_path = pjoin(axis_path, 'images')
        dr = DCMreaderVM(images_path)
        if not (os.path.exists(pjoin(axis_path, 'contours.con'))):
            return None
        cr = CONreaderVM(pjoin(axis_path, 'contours.con'))
        images, ROI = get_images_sa(dr, cr)
    elif axis == 'sale':
        dr = SaleReader(axis_path)
        images = get_images_sale(dr)
        ROI = None
    else:
        logger.error(r"Axis was not 'sa' nor 'sale'")
        return None

    if len(images) == 0:
        return None

    patient_data = dr.patient_data
    label = get_label(patient_path)

    return Patient(patient_id, axis, images, patient_data, label, SA_ROI=ROI)
Beispiel #4
0
# Reads the sa folder wiht dicom files and contours
# then draws the contours on the images.

from con_reader import CONreaderVM
from dicom_reader import DCMreaderVM
from con2img import draw_contourmtcs2image as draw


image_folder = 'C:\\dev\\LHYP\\sample\\13457546AMR801\\sa\\images'
con_file = 'C:\\dev\\LHYP\\sample\\13457546AMR801\\sa\\contours.con'

# reading the dicom files
dr = DCMreaderVM(image_folder)

# reading the contours
cr = CONreaderVM(con_file)
contours = cr.get_hierarchical_contours()

# drawing the contours for the images
for slc in contours:
    for frm in contours[slc]:
        image = dr.get_image(slc, frm)  # numpy array
        cntrs = []
        rgbs = []
        for mode in contours[slc][frm]:
            # choose color
            if mode == 'ln':
                rgb = [1, 0, 0]
            elif mode == 'lp':
                rgb = [0, 1, 0]
            elif mode == 'rn':
Beispiel #5
0
def get_patient(folder_in, patient):
    
    temp_patient = Patient()
    path = folder_in + patient 
    
    # get pathology from meta.txt
    meta = open(path + '/meta.txt','rt')
    line = meta.readline()
    temp_patient.pathology = line.split("Pathology: ")[1].split(' \n')[0]
    meta.close()
    
    # check if images folder is empty, print Error if yes
    if len(os.listdir(path+'/sa/images')) != 0:
        # read dicom
        dr=DCMreaderVM(path + '/sa/images')
        # check if dicom is broken, print error if yes
        if dr.broken is not True:
            # get contours from con file
            con_path = path + '/sa/contours.con'
            if not os.path.exists(con_path):
                print("No contour file exists: {}".format(path))
                return None
            cr=CONreaderVM(con_path)
            contours = cr.get_hierarchical_contours()
            # create temorary variables for contours and dcm images
            tmp_dcm = []
            tmp_contours = []
            # get indices of slices with contour
            slice_keys=list(contours.keys())    
            # get middle index in countours 
            if (len(contours) % 2) != 0: 
                mid_idx = int((len(contours)-1)/2)
            else:
                mid_idx = int(len(contours)/2)
            # store the indices of the 7 slice we want to use
            slice_indices=[
                slice_keys[2],
                slice_keys[3],
                slice_keys[mid_idx-1],
                slice_keys[mid_idx],
                slice_keys[mid_idx+1],
                slice_keys[-4],
                slice_keys[-3]
            ]          
            # loop through contours using slice_indices
            # store images in tmp_dcm, call im_conv to convert images (filter, resclale, uint8)
            # check how many frames on one slice (frame_keys)
            # save contours and image for the given frame
            for slc in slice_indices:
                frame_keys = list(contours[slc].keys())
                if len(frame_keys) == 2:
                    tmp_dcm.append(im_conv(dr.dcm_images[slc][frame_keys[0]]))
                    tmp_contours.append(contours[slc][frame_keys[0]])
                    tmp_dcm.append(im_conv(dr.dcm_images[slc][frame_keys[1]]))
                    tmp_contours.append(contours[slc][frame_keys[1]])

                elif len(frame_keys) > 2:
                    tmp_dcm.append(im_conv(dr.dcm_images[slc][frame_keys[0]]))
                    tmp_contours.append(contours[slc][frame_keys[0]])
                    tmp_dcm.append(im_conv(dr.dcm_images[slc][frame_keys[-1]]))
                    tmp_contours.append(contours[slc][frame_keys[-1]])

                elif len(frame_keys) < 2:
                    if len(frame_keys) == 1:
                        tmp_dcm.append(im_conv(dr.dcm_images[slc][frame_keys[0]]))
                        tmp_contours.append(contours[slc][frame_keys[0]])
                        if frame_keys[0] > 10:
                            tmp_dcm.append(im_conv(dr.dcm_images[slc][frame_keys[0]-10]))
                            tmp_contours.append(None)
                        else:
                            tmp_dcm.append(im_conv(dr.dcm_images[slc][frame_keys[0]+10]))
                            tmp_contours.append(None)
                    else:
                        tmp_dcm.append(im_conv(dr.dcm_images[slc][8]))
                        tmp_contours.append(None)
                        tmp_dcm.append(im_conv(dr.dcm_images[slc][20]))
                        tmp_contours.append(None)
    
            #add temporary dcm image list and contours to temp_patient
            temp_patient.dcm_images = tmp_dcm 
            temp_patient.contours = tmp_contours
            
            # get data from con file (CONreaderVM)
            if cr.volume_data['Study_id='] != None:
                temp_patient.study_id = cr.volume_data['Study_id='].split('\n')[0]
            if cr.volume_data['Patient_gender='] != None:
                temp_patient.gender = cr.volume_data['Patient_gender='].split('\n')[0]
            if cr.volume_data['Field_of_view='] != None:
                temp_patient.fov=[]
                temp_patient.fov.append(cr.volume_data['Field_of_view='].split(' ')[0].split('x')[0])
                temp_patient.fov.append(cr.volume_data['Field_of_view='].split(' ')[0].split('x')[1])
            if cr.volume_data['Slicethickness='] != None:
                temp_patient.slicethickness = cr.volume_data['Slicethickness='].split(' ')[0]
            if cr.volume_data['Patient_height='] != None:
                temp_patient.height = cr.volume_data['Patient_height='].split(' ')[0]
            if cr.volume_data['Patient_weight='] != None:
                temp_patient.weight = cr.volume_data['Patient_weight='].split(' ')[0]

            # get pixel_spacing from dicom
            temp_patient.pixel_spacing = dr.pixel_spacing 
            temp_patient.num_slices = dr.num_slices
            return temp_patient
                          
        else:
            print('Error: DCMreaderVM at {}/sa/images is broken'.format(path))
            return None
    else:
        print('Error: ../images folder at {}/sa/images is empty'. format(path))
        return None
Beispiel #6
0
    for seq_index in range(dr.num_sequences):
        for frame_index in range(dr.num_frames_per_sequence):
            ds = dcmread(dr.get_path(seq_index, frame_index))
            image = dr.get_image(seq_index, frame_index)
            image = process(image, ds)
            image = ((image - image.min()) *
                     (1 / (image.max() - image.min()) * 255)).astype('uint8')
            images.append(Image.fromarray(image))
    return images


axis = 'sa'
if 'sale' in dicoms_path: axis = 'sale'

reader = DCMreaderVM(dicoms_path) if axis == 'sa' else SaleReader(dicoms_path)

print('Reading frames from dicom')

os.makedirs('dicom_gifs', exist_ok=True)
save_path = os.path.join('dicom_gifs', f"{dicoms_path}.gif")

frames = get_sa_images(reader) if axis == 'sa' else get_sale_images(reader)

print(f'Saving to {save_path}')
frames[0].save(save_path,
               save_all=True,
               append_images=frames[1:],
               duration=duration,
               loop=0)