def load_morphace():
    # - Landmarks are a subset of vertices from the morphable model (indexes are defined by the annotation file provided), that's why you are inferring landmarks.
    # load data, filter to 68 landmarks
    # TODO: does this clash with the 30/20 filter?
    vertex_idxs = load_landmarks()
    (texture, identity, expression, triangles) = load_data()
    for pca in (identity, expression, texture):
        pca.mean = pca.mean[vertex_idxs]
        pca.pc = pca.pc[vertex_idxs]
    return (texture, identity, expression, triangles)
Ejemplo n.º 2
0
def main():

    # load data
    color, pca_id, pca_exp, tri = load_data()
    color = color.mean
    v_idx = load_landmarks()

    # create temporary sample data
    alpha, delta, omega, t, im = create_test_data(pca_id, pca_exp, color, tri)

    # create model and texture it
    resolution = tuple(im.shape[:2][::-1])
    geo_, geo = construct_model(pca_id, pca_exp, alpha, delta, omega, t,
                                resolution)
    color_ = determine_texture(geo_, im)
    im_ = geo_to_im(geo, color_, tri)

    # plot results
    fig, axarr = plt.subplots(1, 3)

    axarr[0].set_title('Ground-truth')
    axarr[0].imshow(im)

    axarr[1].set_title('Model on ground-truth')
    axarr[1].imshow(im)
    axarr[1].scatter(geo_[::20, 0], geo_[::20, 1], s=0.1, c='b')
    axarr[1].scatter(geo_[v_idx, 0], geo_[v_idx, 1], s=8, c='r')
    axarr[1].set_xlim([0, resolution[0]])
    axarr[1].set_ylim([resolution[1], 0])

    axarr[2].set_title('Textured model')
    axarr[2].imshow(im_)
    axarr[2].set_xlim([0, resolution[0]])
    axarr[2].set_ylim([resolution[1], 0])

    plt.tight_layout()
    plt.show()

    return
Ejemplo n.º 3
0
def create_training_dataset(results_path, dataset_path, size, mode='min'):
    show = False
    ids = range(0, 481)
    for current_id in ids:
        current_id = str(current_id)
        case_path = os.path.join(results_path, current_id)
        transformed_target_path = os.path.join(case_path,
                                               "transformed_target.mha")
        source_path = os.path.join(case_path, "source.mha")

        transformed_target = sitk.GetArrayFromImage(
            sitk.ReadImage(transformed_target_path))
        source = sitk.GetArrayFromImage(sitk.ReadImage(source_path))

        t_source = torch.from_numpy(source)
        t_target = torch.from_numpy(transformed_target)
        if mode == 'min':
            new_shape = utils.calculate_new_shape_min(
                (t_source.size(0), t_source.size(1)), size)
            if min(new_shape) == min(source.shape):
                print("Resampling not required")
                resampled_source = t_source
                resampled_target = t_target
            else:
                resampled_source = utils.resample_tensor(t_source, new_shape)
                resampled_target = utils.resample_tensor(t_target, new_shape)
        elif mode == 'max':
            new_shape = utils.calculate_new_shape_max(
                (t_source.size(0), t_source.size(1)), size)
            if max(new_shape) == max(source.shape):
                print("Resampling not required")
                resampled_source = t_source
                resampled_target = t_target
            else:
                resampled_source = utils.resample_tensor(t_source, new_shape)
                resampled_target = utils.resample_tensor(t_target, new_shape)

        transformed_target_resampled = resampled_target.numpy()
        source_resampled = resampled_source.numpy()

        target_landmarks_path = os.path.join(case_path, "target_landmarks.csv")
        try:
            target_landmarks = utils.load_landmarks(target_landmarks_path)
            status = "training"
        except:
            status = "evaluation"

        print("Current ID: ", current_id)
        print("Transformed target shape: ", transformed_target.shape)
        print("Source shape: ", source.shape)
        print("Resampled target shape: ", transformed_target_resampled.shape)
        print("Resampled source shape: ", source_resampled.shape)

        if show:
            plt.figure()
            plt.subplot(2, 2, 1)
            plt.imshow(source, cmap='gray')
            plt.axis('off')
            plt.subplot(2, 2, 2)
            plt.imshow(transformed_target, cmap='gray')
            plt.axis('off')
            plt.subplot(2, 2, 3)
            plt.imshow(source_resampled, cmap='gray')
            plt.axis('off')
            plt.subplot(2, 2, 4)
            plt.imshow(transformed_target_resampled, cmap='gray')
            plt.axis('off')
            plt.show()

        to_save_source = sitk.GetImageFromArray(transformed_target_resampled)
        to_save_target = sitk.GetImageFromArray(source_resampled)

        output_path = os.path.join(dataset_path, status, current_id)
        if not os.path.isdir(output_path):
            os.makedirs(output_path)

        source_output_path = os.path.join(output_path, "source.mha")
        target_output_path = os.path.join(output_path, "target.mha")
        sitk.WriteImage(to_save_source, source_output_path)
        sitk.WriteImage(to_save_target, target_output_path)
Ejemplo n.º 4
0
def parse_dataset(csv_path, dataset_path, output_path, masks_path=None):
    output_max_size = 4096
    show = False

    csv_file = pd.read_csv(csv_path)
    for current_case in csv_file.iterrows():
        current_id = current_case[1]['Unnamed: 0']
        size = current_case[1]['Image size [pixels]']
        diagonal = int(current_case[1]['Image diagonal [pixels]'])
        y_size, x_size = int(size.split(",")[0][1:]), int(
            size.split(",")[1][:-1])
        source_path = current_case[1]['Source image']
        target_path = current_case[1]['Target image']
        source_landmarks_path = current_case[1]['Source landmarks']
        target_landmarks_path = current_case[1]['Target landmarks']
        status = current_case[1]['status']

        extension = source_path[-4:]
        if masks_path is not None:
            source_mask_path = os.path.join(
                masks_path, source_path.replace(extension, ".mha"))
            target_mask_path = os.path.join(
                masks_path, target_path.replace(extension, ".mha"))

        source_path = os.path.join(dataset_path,
                                   source_path.replace(extension, ".mha"))
        target_path = os.path.join(dataset_path,
                                   target_path.replace(extension, ".mha"))
        source_landmarks_path = os.path.join(dataset_path,
                                             source_landmarks_path)
        target_landmarks_path = os.path.join(dataset_path,
                                             target_landmarks_path)

        source_landmarks = utils.load_landmarks(source_landmarks_path)
        if status == "training":
            target_landmarks = utils.load_landmarks(target_landmarks_path)

        source = color.rgb2gray(
            sitk.GetArrayFromImage(sitk.ReadImage(source_path)))
        target = color.rgb2gray(
            sitk.GetArrayFromImage(sitk.ReadImage(target_path)))

        if masks_path is not None:
            source_mask = sitk.GetArrayFromImage(
                sitk.ReadImage(source_mask_path)).astype(np.ubyte)
            target_mask = sitk.GetArrayFromImage(
                sitk.ReadImage(target_mask_path)).astype(np.ubyte)
            source_mask = (source_mask / np.max(source_mask))
            target_mask = (target_mask / np.max(target_mask))

        source = 1 - utils.normalize(source)
        target = 1 - utils.normalize(target)

        padded_source, padded_target = utils.pad_images_np(source, target)
        padded_source_landmarks = utils.pad_landmarks(source_landmarks,
                                                      source.shape,
                                                      padded_source.shape)
        if status == "training":
            padded_target_landmarks = utils.pad_landmarks(
                target_landmarks, target.shape, padded_target.shape)

        if masks_path is not None:
            padded_source_mask, padded_target_mask = utils.pad_images_np(
                source_mask, target_mask)

        resample_factor = np.max(padded_source.shape) / output_max_size
        gaussian_sigma = resample_factor / 1.25

        smoothed_source = nd.gaussian_filter(padded_source, gaussian_sigma)
        smoothed_target = nd.gaussian_filter(padded_target, gaussian_sigma)

        resampled_source = utils.resample_image(smoothed_source,
                                                resample_factor)
        resampled_target = utils.resample_image(smoothed_target,
                                                resample_factor)
        resampled_source_landmarks = utils.resample_landmarks(
            padded_source_landmarks, resample_factor)
        if status == "training":
            resampled_target_landmarks = utils.resample_landmarks(
                padded_target_landmarks, resample_factor)

        if masks_path is not None:
            resampled_source_mask = (utils.resample_image(
                padded_source_mask, resample_factor) > 0.5).astype(np.ubyte)
            resampled_target_mask = (utils.resample_image(
                padded_target_mask, resample_factor) > 0.5).astype(np.ubyte)

        print("Current ID: ", current_id)
        print("Y Size, X_size: ", y_size, x_size)
        print("Source path: ", source_path)
        print("Target path: ", target_path)
        print("Source shape: ", source.shape)
        print("Target shape: ", target.shape)
        print("Padded source shape: ", padded_source.shape)
        print("Padded target shape: ", padded_target.shape)
        print("Resampled source shape: ", resampled_source.shape)
        print("Resampled target shape: ", resampled_target.shape)
        print("Source landmarks path: ", source_landmarks_path)
        print("Target landmarks path: ", target_landmarks_path)
        print("Source landmarks shape: ", source_landmarks.shape)
        print("Status: ", status)
        print("Resample factor: ", resample_factor)
        if status == "training":
            print("Target landmarks shape: ", target_landmarks.shape)
            try:
                print(
                    "Initial Median TRE: ",
                    np.median(
                        utils.calculate_tre(source_landmarks,
                                            target_landmarks)))
                print(
                    "Resampled Median TRE: ",
                    np.median(
                        utils.calculate_tre(resampled_source_landmarks,
                                            resampled_target_landmarks)))
            except:
                print("Unequal number of landmarks.")
        print()

        to_save_source_mha = sitk.GetImageFromArray(
            (utils.normalize(resampled_source).astype(np.float32)))
        to_save_target_mha = sitk.GetImageFromArray(
            (utils.normalize(resampled_target).astype(np.float32)))
        to_save_source_jpg = sitk.GetImageFromArray(
            ((utils.normalize(resampled_source).astype(np.float32)) *
             255).astype(np.ubyte))
        to_save_target_jpg = sitk.GetImageFromArray(
            ((utils.normalize(resampled_target).astype(np.float32)) *
             255).astype(np.ubyte))
        to_save_source_landmarks = resampled_source_landmarks.astype(
            np.float32)
        if status == "training":
            to_save_target_landmarks = resampled_target_landmarks.astype(
                np.float32)

        if masks_path is not None:
            to_save_source_mask_mha = sitk.GetImageFromArray(
                resampled_source_mask.astype(np.ubyte))
            to_save_target_mask_mha = sitk.GetImageFromArray(
                resampled_target_mask.astype(np.ubyte))
            to_save_source_mask_jpg = sitk.GetImageFromArray(
                (resampled_source_mask * 255).astype(np.ubyte))
            to_save_target_mask_jpg = sitk.GetImageFromArray(
                (resampled_target_mask * 255).astype(np.ubyte))

        to_save_source_mha_path = os.path.join(output_path, str(current_id),
                                               "source.mha")
        to_save_target_mha_path = os.path.join(output_path, str(current_id),
                                               "target.mha")
        to_save_source_jpg_path = os.path.join(output_path, str(current_id),
                                               "source.jpg")
        to_save_target_jpg_path = os.path.join(output_path, str(current_id),
                                               "target.jpg")
        to_save_source_landmarks_path = os.path.join(output_path,
                                                     str(current_id),
                                                     "source_landmarks.csv")
        if status == "training":
            to_save_target_landmarks_path = os.path.join(
                output_path, str(current_id), "target_landmarks.csv")

        if masks_path is not None:
            to_save_source_mask_mha_path = os.path.join(
                output_path, str(current_id), "source_mask.mha")
            to_save_target_mask_mha_path = os.path.join(
                output_path, str(current_id), "target_mask.mha")
            to_save_source_mask_jpg_path = os.path.join(
                output_path, str(current_id), "source_mask.jpg")
            to_save_target_mask_jpg_path = os.path.join(
                output_path, str(current_id), "target_mask.jpg")

        if not os.path.isdir(os.path.dirname(to_save_source_mha_path)):
            os.makedirs(os.path.dirname(to_save_source_mha_path))

        sitk.WriteImage(to_save_source_mha, to_save_source_mha_path)
        sitk.WriteImage(to_save_target_mha, to_save_target_mha_path)
        sitk.WriteImage(to_save_source_jpg, to_save_source_jpg_path)
        sitk.WriteImage(to_save_target_jpg, to_save_target_jpg_path)
        utils.save_landmarks(to_save_source_landmarks,
                             to_save_source_landmarks_path)
        if status == "training":
            utils.save_landmarks(to_save_target_landmarks,
                                 to_save_target_landmarks_path)

        if masks_path is not None:
            sitk.WriteImage(to_save_source_mask_mha,
                            to_save_source_mask_mha_path)
            sitk.WriteImage(to_save_target_mask_mha,
                            to_save_target_mask_mha_path)
            sitk.WriteImage(to_save_source_mask_jpg,
                            to_save_source_mask_jpg_path)
            sitk.WriteImage(to_save_target_mask_jpg,
                            to_save_target_mask_jpg_path)

        if show:
            plt.figure()
            no_rows = 1 if masks_path is None else 2
            plt.subplot(no_rows, 2, 1)
            plt.imshow(source, cmap='gray')
            plt.plot(source_landmarks[:, 0], source_landmarks[:, 1], "r*")
            plt.title("Source")
            plt.subplot(no_rows, 2, 2)
            plt.imshow(target, cmap='gray')
            if status == "training":
                plt.plot(target_landmarks[:, 0], target_landmarks[:, 1], "r*")
            plt.title("Target")
            if masks_path is not None:
                plt.subplot(no_rows, 2, 3)
                plt.imshow(source_mask, cmap='gray')
                plt.title("Source Mask")
                plt.subplot(no_rows, 2, 4)
                plt.imshow(target_mask, cmap='gray')
                plt.title("Target Mask")

            plt.figure()
            plt.subplot(no_rows, 2, 1)
            plt.imshow(padded_source, cmap='gray')
            plt.plot(padded_source_landmarks[:, 0],
                     padded_source_landmarks[:, 1], "r*")
            plt.title("Padded Source")
            plt.subplot(no_rows, 2, 2)
            plt.imshow(padded_target, cmap='gray')
            if status == "training":
                plt.plot(padded_target_landmarks[:, 0],
                         padded_target_landmarks[:, 1], "r*")
            plt.title("Padded Target")
            if masks_path is not None:
                plt.subplot(no_rows, 2, 3)
                plt.imshow(padded_source_mask, cmap='gray')
                plt.title("Padded Source Mask")
                plt.subplot(no_rows, 2, 4)
                plt.imshow(padded_target_mask, cmap='gray')
                plt.title("Padded Target Mask")

            plt.figure()
            plt.subplot(1, 2, 1)
            plt.imshow(smoothed_source, cmap='gray')
            plt.plot(padded_source_landmarks[:, 0],
                     padded_source_landmarks[:, 1], "r*")
            plt.title("Smoothed Source")
            plt.subplot(1, 2, 2)
            plt.imshow(smoothed_target, cmap='gray')
            if status == "training":
                plt.plot(padded_target_landmarks[:, 0],
                         padded_target_landmarks[:, 1], "r*")
            plt.title("Smoothed Target")

            plt.figure()
            plt.subplot(no_rows, 2, 1)
            plt.imshow(resampled_source, cmap='gray')
            plt.plot(resampled_source_landmarks[:, 0],
                     resampled_source_landmarks[:, 1], "r*")
            plt.title("Resampled Source")
            plt.subplot(no_rows, 2, 2)
            plt.imshow(resampled_target, cmap='gray')
            if status == "training":
                plt.plot(resampled_target_landmarks[:, 0],
                         resampled_target_landmarks[:, 1], "r*")
            plt.title("Resampled Target")
            if masks_path is not None:
                plt.subplot(no_rows, 2, 3)
                plt.imshow(resampled_source_mask, cmap='gray')
                plt.title("Resampled Source Mask")
                plt.subplot(no_rows, 2, 4)
                plt.imshow(resampled_target_mask, cmap='gray')
                plt.title("Resampled Target Mask")
            plt.show()
def main():

    # load data
    color, pca_id, pca_exp, tri = load_data()
    color = color.mean
    v_idx = load_landmarks()

    # set geometry (use mean value)
    geo = pca_id.sample(0.0)

    if ARGS.debug:

        # parameters
        omega = [0.0, 0.0, 0.0]
        t = [0.0, 0.0, 0.0]

        # reproduce debug data
        im = geo_to_im(geo, color, tri)
        resolution = tuple(im.shape[:2][::-1])
        M = construct_obj_to_cam(omega, t, resolution)
        geo_ = apply_transform(geo, M)

        # load debug images
        test = plt.imread('debug_images/test.png')
        debug0000 = plt.imread('debug_images/debug0000.png')

        # plot results
        fig, axarr = plt.subplots(1, 3)

        axarr[0].set_title('test.png')
        axarr[0].imshow(test)

        axarr[1].set_title('debug0000.png')
        axarr[1].imshow(debug0000)

        axarr[2].set_title('reproduction')
        axarr[2].imshow(im)
        axarr[2].scatter(geo_[::20, 0], geo_[::20, 1], s=0.1, c='b')
        axarr[2].scatter(geo_[v_idx, 0], geo_[v_idx, 1], s=8, c='r')
        axarr[2].set_xlim([0, resolution[0]])
        axarr[2].set_ylim([resolution[1], 0])

        plt.tight_layout()

    else:

        # determine left and right rotated images
        R_l = construct_R(0, 10, 0)
        R_r = construct_R(0, -10, 0)
        geo_l = apply_transform(geo, R_l)
        geo_r = apply_transform(geo, R_r)

        # plot rotated images
        im_l = geo_to_im(geo_l, color, tri)
        im_r = geo_to_im(geo_r, color, tri)
        fig, axarr = plt.subplots(2)
        axarr[0].set_title('10 degree y-rotation')
        axarr[0].imshow(im_l)
        axarr[1].set_title('-10 degree y-rotation')
        axarr[1].imshow(im_r)
        plt.tight_layout()

        # parameters
        omega = [0.0, 10.0, 0.0]
        t = [0.0, 0.0, 0.0]
        resolution = tuple(im_l.shape[:2][::-1])

        # create rotated model
        M = construct_obj_to_cam(omega, t, resolution)
        geo_ = apply_transform(geo, M)

        # plot landmarks
        fig, ax = plt.subplots(1)
        ax.set_title('10 degree rotation landmarks')
        ax.scatter(geo_[v_idx, 0], geo_[v_idx, 1], c='b', s=8)
        for i in range(len(v_idx)):
            ax.text(geo_[v_idx[i], 0], geo_[v_idx[i], 1], i, fontsize=8)
        ax.axis('equal')
        ylim = ax.get_ylim()
        ax.set_ylim(ylim[::-1])
        plt.tight_layout()

    plt.show()

    return
Ejemplo n.º 6
0
def run_single(params):
    source_path = params['source_path']
    target_path = params['target_path']
    source_landmarks_path = params['source_landmarks_path']
    target_landmarks_path = params['target_landmarks_path']
    status = params['status']
    y_size = params['y_size']
    x_size = params['x_size']
    results_path = params['output_path']
    current_id = params['id']

    if not os.path.isdir(os.path.join(results_path, str(current_id))):
        os.mkdir(os.path.join(results_path, str(current_id)))

    source = utils.load_image(source_path)
    target = utils.load_image(target_path)

    source_landmarks = utils.load_landmarks(source_landmarks_path)
    if status == "training":
        print()
        print("Training case.")
        target_landmarks = utils.load_landmarks(target_landmarks_path)
    else:
        print()
        print("Evaluation case.")

    p_target, p_source, ia_target, ng_target, nr_target, i_u_x, i_u_y, u_x_nr, u_y_nr, warp_resampled_landmarks, warp_original_landmarks, return_dict = am.anhir_method(target, source)
    transformed_landmarks = warp_original_landmarks(source_landmarks)

    p_target = utils.normalize(p_target)
    p_source = utils.normalize(p_source)
    ia_target = utils.normalize(ia_target)
    ng_target = utils.normalize(ng_target)
    nr_target = utils.normalize(nr_target)

    p_target_i = utils.to_image(p_target)
    p_source_i = utils.to_image(p_source)
    ia_target_i = utils.to_image(ia_target)
    ng_target_i = utils.to_image(ng_target)
    nr_target_i = utils.to_image(nr_target)
    
    json_return_dict = json.dumps(return_dict)
    with open(os.path.join(results_path, str(current_id), "info.json"), "w") as f:
        f.write(json_return_dict)

    if status == "training":
        try:
            o_median = np.median(utils.rtre(source_landmarks, target_landmarks, x_size, y_size))
            r_median = np.median(utils.rtre(transformed_landmarks, target_landmarks, x_size, y_size))
            print("Initial rTRE: ", o_median)
            print("Resulting rTRE: ", r_median)
            string_to_save = "Initial TRE: " + str(o_median) + "\n" + "Resulting TRE: " + str(r_median)
            txt_path = os.path.join(results_path, str(current_id), "tre.txt")
            with open(txt_path, "w") as file:
                file.write(string_to_save)
        except:
            string_to_save = "Landmarks ERROR"
            txt_path = os.path.join(results_path, str(current_id), "tre_error.txt")
            with open(txt_path, "w") as file:
                file.write(string_to_save)     

    source_save_path = os.path.join(results_path, str(current_id), "source.png")
    target_save_path = os.path.join(results_path, str(current_id), "target.png")
    transformed_target_g_save_path = os.path.join(results_path, str(current_id), "target_ng.png")
    transformed_target_save_path = os.path.join(results_path, str(current_id), "target_nr.png")
    ia_target_save_path = os.path.join(results_path, str(current_id), "target_ia.png")
    sitk.WriteImage(p_source_i, source_save_path)
    sitk.WriteImage(p_target_i, target_save_path)
    sitk.WriteImage(ng_target_i, transformed_target_g_save_path)
    sitk.WriteImage(nr_target_i, transformed_target_save_path)
    sitk.WriteImage(ia_target_i, ia_target_save_path)

    transformed_source_landmarks_path = os.path.join(results_path, str(current_id), "transformed_source_landmarks.csv")
    utils.save_landmarks(transformed_source_landmarks_path, transformed_landmarks)

    return_dict = dict()
    return_dict['transformed_source_landmarks_path'] = os.path.join(str(current_id), "transformed_source_landmarks.csv")
    if status == "training":
        try:
            return_dict['initial_tre'] = o_median
            return_dict['resulting_tre'] = r_median
        except:
            return_dict['initial_tre'] = 0
            return_dict['resulting_tre'] = 0
    return return_dict
def prepare_submission():
    if not os.path.isdir(submission_path):
        os.makedirs(submission_path)
    output_csv_path = os.path.join(submission_path, "registration-results.csv")
    prepare_output_csv(csv_path, output_csv_path)

    ids = range(0, 481)
    for current_id in ids:
        current_id = str(current_id)
        case_path = os.path.join(submission_path, current_id)
        if not os.path.isdir(case_path):
            os.makedirs(case_path)

        source_landmarks_path = os.path.join(results_path, current_id, "source_landmarks.csv")
        transformed_source_landmarks_path = os.path.join(results_path, current_id, "transformed_source_landmarks.csv")
        target_landmarks_path = os.path.join(results_path, current_id, "target_landmarks.csv")
        time_path = os.path.join(results_path, current_id, "time.txt")

        source_landmarks = utils.load_landmarks(source_landmarks_path)
        transformed_source_landmarks = utils.load_landmarks(transformed_source_landmarks_path)
        try:
            target_landmarks = utils.load_landmarks(target_landmarks_path)
            if target_landmarks.shape == transformed_source_landmarks.shape:
                status = "training"
            else:
                status = "evaluation"
        except:
            status = "evaluation"

        with open(time_path, "r") as file:
            execution_time = file.read()

        dataframe = pd.read_csv(output_csv_path)
        del dataframe['Unnamed: 0']
        print()
        print("Current ID: ",  current_id)
        print("Execution time: ", execution_time)

        current_id = int(current_id)
        org_source_path = dataframe['Source image'][current_id]
        org_target_path = dataframe['Target image'][current_id]
        sizes = dataframe['Image size [pixels]'][current_id]
        sizes = sizes[:].split(", ")
        y_size = int(sizes[0][1:])
        x_size = int(sizes[1][:-1])
        diagonal = np.sqrt(y_size**2 + x_size**2)
        current_id = str(current_id)
        if ".jpg" in org_source_path:
            org_source_path = org_source_path.replace(".jpg", ".mha")
            org_target_path = org_target_path.replace(".jpg", ".mha")
        elif ".png" in org_source_path:
            org_source_path = org_source_path.replace(".png", ".mha")
            org_target_path = org_target_path.replace(".png", ".mha")

        source_path = os.path.join(results_path, current_id, "source.mha")
        original_source_path = os.path.join(original_data_path, org_source_path)
        original_target_path = os.path.join(original_data_path, org_target_path)

        def get_size(path):
            reader = sitk.ImageFileReader()
            reader.SetFileName(path)
            reader.LoadPrivateTagsOn()
            reader.ReadImageInformation()
            size = reader.GetSize()
            return size

        source_size = get_size(source_path)
        original_source_size = get_size(original_source_path)
        original_target_size = get_size(original_target_path)

        print("Source path: ", source_path)
        print("Original source path: ", original_source_path)
        print("Original target path: ", original_target_path)
        print("Resampled size: ", source_size)
        print("Original source size: ", original_source_size)
        print("Original target size: ", original_target_size)

        if status == "training":
            print("Resampled median initial rTRE: ", np.median(utils.calculate_rtre(source_landmarks, target_landmarks, np.sqrt(source_size[0]**2 + source_size[1]**2))))
            print("Resampled median final rTRE: ", np.median(utils.calculate_rtre(transformed_source_landmarks, target_landmarks, np.sqrt(source_size[0]**2 + source_size[1]**2))))

        _, _, _, _, new_shape = calculate_pad_size(original_source_size, original_target_size)
        resample_ratio = max(new_shape) / max(source_size)
        
        org_source_landmarks = source_landmarks.copy()
        org_source_landmarks[:, 0] =  org_source_landmarks[:, 0] * resample_ratio - (int(np.floor((new_shape[0] - original_source_size[0])/2)))
        org_source_landmarks[:, 1] =  org_source_landmarks[:, 1] * resample_ratio - (int(np.floor((new_shape[1] - original_source_size[1])/2)))

        org_transformed_source_landmarks = transformed_source_landmarks.copy()
        org_transformed_source_landmarks[:, 0] =  org_transformed_source_landmarks[:, 0] * resample_ratio - (int(np.floor((new_shape[0] - original_target_size[0])/2)))
        org_transformed_source_landmarks[:, 1] =  org_transformed_source_landmarks[:, 1] * resample_ratio - (int(np.floor((new_shape[1] - original_target_size[1])/2)))

        if status == "training":
            org_target_landmarks = target_landmarks.copy()
            org_target_landmarks[:, 0] =  org_target_landmarks[:, 0] * resample_ratio - (int(np.floor((new_shape[0] - original_target_size[0])/2)))
            org_target_landmarks[:, 1] =  org_target_landmarks[:, 1] * resample_ratio - (int(np.floor((new_shape[1] - original_target_size[1])/2)))
            i_tre = np.median(utils.calculate_rtre(org_source_landmarks, org_target_landmarks, diagonal))
            f_tre = np.median(utils.calculate_rtre(org_transformed_source_landmarks, org_target_landmarks, diagonal))
            print("Original median initial rTRE: ", i_tre)
            print("Original median final rTRE: ", f_tre)
            dataframe['Initial TRE Median'][int(current_id)] = i_tre
            dataframe['Final TRE Median'][int(current_id)] = f_tre
            try:
                string_to_save = "Initial TRE: " + str(i_tre) + "\n" + "Resulting TRE: " + str(f_tre)
                txt_path = os.path.join(submission_path, str(current_id), "tre.txt")
                with open(txt_path, "w") as file:
                    file.write(string_to_save)
            except:
                pass
        transformed_path = os.path.join(current_id, "transformed_source_landmarks.csv")
        org_src_path = os.path.join(current_id, "org_source_landmarks.csv")
        utils.save_landmarks_submission(org_transformed_source_landmarks, os.path.join(submission_path, transformed_path))
        utils.save_landmarks_submission(org_source_landmarks, os.path.join(submission_path, org_src_path))
        if status == "training":
            org_trg_path = os.path.join(current_id, "org_target_landmarks.csv")
            utils.save_landmarks_submission(org_target_landmarks, os.path.join(submission_path, org_trg_path))

        dataframe['Execution time [minutes]'][int(current_id)] = str(float(execution_time) / 60)
        dataframe['Warped source landmarks'][int(current_id)] = transformed_path
        dataframe.to_csv(output_csv_path)
Ejemplo n.º 8
0
def main():
    source_path = None  # Source path
    target_path = None  # Target path

    source_landmarks_path = None  # Source landmarks path
    target_landmarks_path = None  # Target landmarks path

    source_landmarks = utils.load_landmarks(source_landmarks_path)
    target_landmarks = utils.load_landmarks(target_landmarks_path)
    source = utils.load_image(source_path)
    target = utils.load_image(target_path)

    p_source, p_target, ia_source, ng_source, nr_source, i_u_x, i_u_y, u_x_nr, u_y_nr, warp_resampled_landmarks, warp_original_landmarks, return_dict = am.anhir_method(
        target, source)

    transformed_source_landmarks = warp_original_landmarks(source_landmarks)

    resampled_source_landmarks, transformed_resampled_source_landmarks, resampled_target_landmarks = warp_resampled_landmarks(
        source_landmarks, target_landmarks)

    y_size, x_size = np.shape(target)
    print("Initial original rTRE: ")
    utils.print_rtre(source_landmarks, target_landmarks, x_size, y_size)
    print("Transformed original rTRE: ")
    utils.print_rtre(transformed_source_landmarks, target_landmarks, x_size,
                     y_size)

    y_size, x_size = np.shape(p_target)
    print("Initial resampled rTRE: ")
    utils.print_rtre(resampled_source_landmarks, resampled_target_landmarks,
                     x_size, y_size)
    print("Transformed resampled rTRE: ")
    utils.print_rtre(transformed_resampled_source_landmarks,
                     resampled_target_landmarks, x_size, y_size)

    print(return_dict)

    plt.figure()
    plt.subplot(1, 2, 1)
    plt.imshow(source, cmap='gray')
    colors = utils.plot_landmarks(source_landmarks, "*")
    plt.axis('off')
    plt.subplot(1, 2, 2)
    plt.imshow(target, cmap='gray')
    utils.plot_landmarks(target_landmarks, "*", colors)
    utils.plot_landmarks(transformed_source_landmarks, ".", colors)
    plt.axis('off')

    plt.figure()
    plt.subplot(1, 3, 1)
    plt.imshow(p_target, cmap='gray')
    colors = utils.plot_landmarks(resampled_source_landmarks, "*")
    plt.axis('off')
    plt.subplot(1, 3, 2)
    plt.imshow(p_source, cmap='gray')
    utils.plot_landmarks(resampled_target_landmarks, "*", colors)
    utils.plot_landmarks(transformed_resampled_source_landmarks, ".", colors)
    plt.axis('off')
    plt.subplot(1, 3, 3)
    plt.imshow(nr_source, cmap='gray')
    plt.axis('off')

    plt.show()