def create_slices(imagePath, maskPath, cads):
    # if os.path.isfile(imagePath.replace('original', SAVE_FOLDER_image)) == False:
    img, origin, spacing = load_itk(imagePath)
    mask, _, _ = load_itk(maskPath)

    # determine the cads in a lung from csv file
    imageName = os.path.split(imagePath)[1].replace('.mhd', '')
    image_cads = cads[cads['seriesuid'] == imageName]

    # calculate resize factor
    resize_factor = spacing / RESIZE_SPACING
    new_real_shape = img.shape * resize_factor
    new_shape = np.round(new_real_shape)
    real_resize = new_shape / img.shape
    new_spacing = spacing / real_resize

    # resize image & resize lung-mask
    lung_img = scipy.ndimage.interpolation.zoom(img, real_resize)
    lung_mask = scipy.ndimage.interpolation.zoom(mask, real_resize)
    # print lung_mask.shape()

    # lung_mask to 0-1
    lung_mask[lung_mask > 0] = 1

    # create nodule mask
    nodule_mask = draw_circles(lung_img, image_cads, origin, new_spacing)

    # Determine which slices contain nodules
    sliceList = []
    for z in range(nodule_mask.shape[2]):
        if np.sum(nodule_mask[:, :, z]) > 0:
            sliceList.append(z)

    # save slices
    for z in sliceList:
        lung_slice = lung_img[:, :, z]
        lung_mask_slice = lung_mask[:, :, z]
        nodule_mask_slice = nodule_mask[:, :, z]

        # padding to 512x512
        original_shape = lung_img.shape
        lung_slice_512 = np.zeros((512, 512)) - 3000
        lung_mask_slice_512 = np.zeros((512, 512))
        nodule_mask_slice_512 = np.zeros((512, 512))

        offset = (512 - original_shape[1])
        upper_offset = np.round(offset / 2)
        lower_offset = offset - upper_offset

        new_origin = voxel_2_world([-upper_offset, -lower_offset, 0], origin,
                                   new_spacing)

        lung_slice_512[upper_offset:-lower_offset,
                       upper_offset:-lower_offset] = lung_slice
        lung_mask_slice_512[upper_offset:-lower_offset,
                            upper_offset:-lower_offset] = lung_mask_slice
        nodule_mask_slice_512[upper_offset:-lower_offset,
                              upper_offset:-lower_offset] = nodule_mask_slice

        # save the lung slice
        savePath = imagePath.replace('original_lungs', SAVE_FOLDER_image)
        f = gzip.open(savePath.replace('.mhd', '_slice{}.pkl.gz'.format(z)),
                      'wb')
        pickle.dump(lung_slice_512, f, protocol=-1)
        pickle.dump(new_spacing, f, protocol=-1)
        pickle.dump(new_origin, f, protocol=-1)
        f.close()

        savePath = imagePath.replace('original_lungs', SAVE_FOLDER_lung_mask)
        f = gzip.open(savePath.replace('.mhd', '_slice{}.pkl.gz'.format(z)),
                      'wb')
        pickle.dump(lung_mask_slice_512, f, protocol=-1)
        pickle.dump(new_spacing, f, protocol=-1)
        pickle.dump(new_origin, f, protocol=-1)
        f.close()

        savePath = imagePath.replace('original_lungs', SAVE_FOLDER_nodule_mask)
        f = gzip.open(savePath.replace('.mhd', '_slice{}.pkl.gz'.format(z)),
                      'wb')
        pickle.dump(nodule_mask_slice_512, f, protocol=-1)
        pickle.dump(new_spacing, f, protocol=-1)
        pickle.dump(new_origin, f, protocol=-1)
        f.close()
Exemple #2
0
def process_image(image_path, candidates, save_dir):
    # load image
    image, origin, spacing = load_itk(image_path)

    # calculate resize factor
    resize_factor = spacing / OUTPUT_SPACING
    new_real_shape = image.shape * resize_factor
    new_shape = np.round(new_real_shape)
    real_resize = new_shape / image.shape
    new_spacing = spacing / real_resize

    # resize image
    image = scipy.ndimage.interpolation.zoom(image, real_resize)

    # Pad image with offset (OUTPUT_DIM/2) to prevent problems with candidates on edge of image
    offset = OUTPUT_DIM / 2
    image = np.pad(image, offset, 'constant', constant_values=0)

    # Make a indixlist of the candidates of the image
    image_name = os.path.split(image_path)[1].replace('.mhd', '')
    indices = candidates[candidates['image_name'] == image_name].index

    # loop through the candidates within this image
    for i in indices:
        # get row data and nodule voxel coords
        row = candidates.iloc[i]
        world_coords = np.array([row.x, row.y, row.z])
        # add offset to voxel coords to cope with padding
        coords = np.floor(world_2_voxel(world_coords, origin,
                                        new_spacing)) + offset
        label = row.label

        # Create xy, xz, yz
        xy_slice = np.transpose(image[coords[0] - offset:coords[0] + offset,
                                      coords[1] - offset:coords[1] + offset,
                                      coords[2]])
        xz_slice = np.rot90(image[coords[0] - offset:coords[0] + offset,
                                  coords[1],
                                  coords[2] - offset:coords[2] + offset])
        yz_slice = np.rot90(image[coords[0],
                                  coords[1] - offset:coords[1] + offset,
                                  coords[2] - offset:coords[2] + offset])

        # UNCOMMENT THESE LINES IF YOU WANT TO MANUALLY COMPARE IMAGES WITH MEVISLAB
        # test_coords means coords you need to look up in mevislab
        # test_coords = world_2_voxel(world_coords,origin,spacing)
        # print 'x:',test_coords[0],'y:',test_coords[1],'z:',test_coords[2]
        # plt.imshow(xy_slice)
        # plt.gray()
        # plt.figure(2)
        # plt.imshow(xz_slice)
        # plt.gray()
        # plt.figure(3)
        # plt.imshow(yz_slice)
        # plt.gray()
        # plt.show()

        # Create output
        output = np.zeros([3, OUTPUT_DIM, OUTPUT_DIM])
        output[0, :, :] = xy_slice
        output[1, :, :] = xz_slice
        output[2, :, :] = yz_slice

        # Determine save_path based on label and indices (need +2 due to starting with zero + header in csv)
        if label:
            save_path = save_dir.format('True') + '/{}.pkl.gz'.format(i + 2)
        else:
            save_path = save_dir.format('False') + '/{}.pkl.gz'.format(i + 2)

        # save with gzip/pickle
        with gzip.open(save_path, 'wb') as f:
            pickle.dump(output, f, protocol=-1)
Exemple #3
0
def process_image(image_path, candidates, save_dir):
    #load image 
    image, origin, spacing = load_itk(image_path)

    #calculate resize factor
    resize_factor = spacing / OUTPUT_SPACING
    new_real_shape = image.shape * resize_factor
    new_shape = np.round(new_real_shape)
    real_resize = new_shape / image.shape
    new_spacing = spacing / real_resize
    
    #resize image
    image = scipy.ndimage.interpolation.zoom(image, real_resize)

    #Pad image with offset (OUTPUT_DIM/2) to prevent problems with candidates on edge of image
    offset = OUTPUT_DIM/2
    image = np.pad(image,offset,'constant',constant_values=0)

    #Make a indixlist of the candidates of the image 
    image_name = os.path.split(image_path)[1].replace('.mhd','')
    indices = candidates[candidates['image_name'] == image_name].index

    #loop through the candidates within this image
    for i in indices:

        #get row data and nodule voxel coords
        row = candidates.iloc[i]
        world_coords = np.array([row.x, row.y, row.z])
        # add offset to voxel coords to cope with padding
        coords = np.floor(world_2_voxel(world_coords,origin,new_spacing)) + offset
        label = row.label

        # Create xy, xz, yz
        xy_slice = np.transpose(image[coords[0]-offset:coords[0]+offset,coords[1]-offset:coords[1]+offset,coords[2]])
        xz_slice = np.rot90(image[coords[0]-offset:coords[0]+offset,coords[1],coords[2]-offset:coords[2]+offset])
        yz_slice = np.rot90(image[coords[0],coords[1]-offset:coords[1]+offset,coords[2]-offset:coords[2]+offset])

        # UNCOMMENT THESE LINES IF YOU WANT TO MANUALLY COMPARE IMAGES WITH MEVISLAB
        # test_coords means coords you need to look up in mevislab
        #test_coords = world_2_voxel(world_coords,origin,spacing)
        #print 'x:',test_coords[0],'y:',test_coords[1],'z:',test_coords[2]
        #plt.imshow(xy_slice)
        #plt.gray()
        #plt.figure(2)
        #plt.imshow(xz_slice)
        #plt.gray()
        #plt.figure(3)
        #plt.imshow(yz_slice)
        #plt.gray()
        #plt.show()

        # Create output
        output = np.zeros([3,OUTPUT_DIM,OUTPUT_DIM])
        output[0,:,:] = xy_slice
        output[1,:,:] = xz_slice
        output[2,:,:] = yz_slice

        # Determine save_path based on label and indices (need +2 due to starting with zero + header in csv)
        if label:
        	save_path = save_dir.format('True') + '/{}.pkl.gz'.format(i+2)
        else:
        	save_path = save_dir.format('False') + '/{}.pkl.gz'.format(i+2)

        # save with gzip/pickle
        with gzip.open(save_path,'wb') as f:
        	pickle.dump(output,f,protocol=-1)
def create_slices(imagePath, maskPath, cads):
    #if os.path.isfile(imagePath.replace('original',SAVE_FOLDER_image)) == False:
    img, origin, spacing = load_itk(imagePath)
    mask, _, _ = load_itk(maskPath)

    #determine the cads in a lung from csv file
    imageName = os.path.split(imagePath)[1].replace('.mhd','')
    image_cads = cads[cads['seriesuid'] == imageName]

    #calculate resize factor
    resize_factor = spacing / RESIZE_SPACING
    new_real_shape = img.shape * resize_factor
    new_shape = np.round(new_real_shape)
    real_resize = new_shape / img.shape
    new_spacing = spacing / real_resize
    
    #resize image & resize lung-mask
    lung_img = scipy.ndimage.interpolation.zoom(img, real_resize)
    lung_mask = scipy.ndimage.interpolation.zoom(mask, real_resize)
    #print lung_mask.shape()

    #lung_mask to 0-1
    lung_mask[lung_mask >0] = 1
    
    #create nodule mask
    nodule_mask = draw_circles(lung_img,image_cads,origin,new_spacing)

    #Determine which slices contain nodules
    sliceList = []
    for z in range(nodule_mask.shape[2]):
        if np.sum(nodule_mask[:,:,z]) > 0:
    	    sliceList.append(z)

    #save slices
    for z in sliceList:
        lung_slice = lung_img[:,:,z]
        lung_mask_slice = lung_mask[:,:,z]
        nodule_mask_slice = nodule_mask[:,:,z]
        
        #padding to 512x512
        original_shape = lung_img.shape
        lung_slice_512 = np.zeros((512,512)) - 3000
        lung_mask_slice_512 = np.zeros((512,512))
        nodule_mask_slice_512 = np.zeros((512,512))

        offset = (512 - original_shape[1])
        upper_offset = np.round(offset/2)
        lower_offset = offset - upper_offset

        new_origin = voxel_2_world([-upper_offset,-lower_offset,0],origin,new_spacing)

        lung_slice_512[upper_offset:-lower_offset,upper_offset:-lower_offset] = lung_slice
        lung_mask_slice_512[upper_offset:-lower_offset,upper_offset:-lower_offset] = lung_mask_slice
        nodule_mask_slice_512[upper_offset:-lower_offset,upper_offset:-lower_offset] = nodule_mask_slice

        #save the lung slice
        savePath = imagePath.replace('original_lungs',SAVE_FOLDER_image)
        file = gzip.open(savePath.replace('.mhd','_slice{}.pkl.gz'.format(z)),'wb')
        pickle.dump(lung_slice_512,file,protocol=-1)
        pickle.dump(new_spacing,file, protocol=-1)
        pickle.dump(new_origin,file, protocol=-1)
        file.close()

        savePath = imagePath.replace('original_lungs',SAVE_FOLDER_lung_mask)
        file = gzip.open(savePath.replace('.mhd','_slice{}.pkl.gz'.format(z)),'wb')
        pickle.dump(lung_mask_slice_512,file,protocol=-1)
        pickle.dump(new_spacing,file, protocol=-1)
        pickle.dump(new_origin,file, protocol=-1)
        file.close()

        savePath = imagePath.replace('original_lungs',SAVE_FOLDER_nodule_mask)
        file = gzip.open(savePath.replace('.mhd','_slice{}.pkl.gz'.format(z)),'wb')
        pickle.dump(nodule_mask_slice_512,file,protocol=-1)
        pickle.dump(new_spacing,file, protocol=-1)
        pickle.dump(new_origin,file, protocol=-1)
        file.close()