Example #1
0
def approximate_image(image, writer, results_dict):
    results_dict["Shape"] = image.shape

    for rank, density in itertools.product(constants.ranks,
                                           constants.densities):
        results_dict["Density"] = density
        results_dict["Rank"] = rank
        low_rank_image = utils.low_rank_approximation(image, rank)

        for method_name in constants.methods:
            results_dict["Algorithm"] = method_name

            method = constants.methods[method_name]
            method.set_data(low_rank_image)
            method.create_sets(constants.train_percentage,
                               constants.test_percentage)

            for similarity_name, number_of_neighbors in itertools.product(
                    constants.similarity_measures,
                    constants.numbers_of_neighbors):

                results_dict["Similarity"] = similarity_name
                results_dict["Number_of_neighbors"] = number_of_neighbors

                similarity = constants.similarity_measures[similarity_name]

                time1 = time.time()
                predicted_image = method.similarity_prediction(
                    similarity, number_of_neighbors)
                time2 = time.time()
                results_dict["Time"] = time2 - time1

                results_dict["Train_error"] = utils.relative_error(
                    predicted_image, low_rank_image, method.train_mask)
                results_dict["Test_error"] = utils.relative_error(
                    predicted_image, low_rank_image, method.test_mask)
                results_dict["Full_error"] = utils.relative_error(
                    predicted_image, low_rank_image)

                writer.writerow(results_dict)
Example #2
0
    def __recalculate_parameters(self, a_row_idx, a_approach_size: PointData.ApproachSide):
        point = self.__points[a_row_idx][self.Column.AMPLITUDE]
        value = self.__points[a_row_idx][self.__side_to_value_column[a_approach_size]]
        if point != 0 and value == 0:
            # Если точка добавлена в таблицу, но еще не измерена
            return

        absolute_error = utils.absolute_error(point, value)
        relative_error = utils.relative_error(point, value, self.normalize_value)

        self.setData(self.index(a_row_idx, self.__side_to_error_column[a_approach_size]), str(absolute_error))
        self.setData(self.index(a_row_idx, self.__side_to_error_percent_column[a_approach_size]), str(relative_error))

        down_value = self.__points[a_row_idx][self.Column.DOWN_VALUE]
        up_value = self.__points[a_row_idx][self.Column.UP_VALUE]
        if (down_value != 0) and (up_value != 0):
            self.setData(self.index(a_row_idx, self.Column.VARIATION), str(utils.variation(down_value, up_value)))
Example #3
0
def plot_results(vhdl_values, numpy_values, axes_data, name):
    error = []
    for index in range(len(vhdl_values)):
        error.append(relative_error(numpy_values[index], vhdl_values[index]))
    error_mean = mean(error)
    variance_ = variance(error, error_mean)
    print('Error mean {} Variance {}'.format(error_mean, variance_))
    fig, axes = plt.subplots(1, 2)
    axes[0].plot(axes_data[:len(vhdl_values)], vhdl_values)
    axes[0].set_title(name)
    axes[0].set_ylabel('Angle')
    axes[0].set_xlabel('Angle')
    axes[1].plot(axes_data[:len(vhdl_values)], error, '--*')
    axes[1].set_title('Relative Error')
    axes[1].set_ylabel('Error (%)')
    axes[1].set_xlabel('Angle')
    axes[1].set_ylim(-0.8, 1.5)
    plt.show()
Example #4
0
          n_neighbors=10,
          geod_n_neighbors=10,
          embedding_dim=3,
          verbose=True).fit()
ptu_time = round(time() - t, 2)
print('ptu time: ', ptu_time)

# Perform Isomap
t = time()
iso = Isomap(n_neighbors=10, n_components=3).fit_transform(exact)
isomap_time = round(time() - t, 2)
print('isomap time: ', isomap_time)

# Align PTU and Isomap to exact parametrization via best isometric
# transformation, and compute errors
ptu = align(ptu, exact)
iso = align(iso, exact)
ptu_error = relative_error(ptu, exact)
iso_error = relative_error(iso, exact)
print('ptu relative error: {}%'.format(ptu_error))
print('isomap relative error: {}%'.format(iso_error))

# Plot results
f = plot_torus(exact,
               ptu,
               iso,
               ptu_time,
               isomap_time,
               hue='normalized_poinwise_error')
plt.show()
          geod_n_neighbors=10,
          embedding_dim=2,
          verbose=True)
ptu.compute_geodesic_distances()
ptu_dists = ptu.ptu_dists
print('Computing PTU dists: done')

# Computing Dijkstra distances
print('Computing Dijkstra dists')
nn = NearestNeighbors(n_neighbors=10)
nn.fit(X)
graph = nn.kneighbors_graph(mode='distance')
dijkstra_dists = graph_shortest_path(graph, directed=False, method='D')
print('Computing Dijkstra dists: done')

ptu_relative_error = relative_error(ptu_dists, true_geod_dists)
dijkstra_relative_error = relative_error(dijkstra_dists, true_geod_dists)
print('PTU geodesic distances relative error (knn connectivity) = {}%'.format(
    ptu_relative_error))
print('Dijkstra geodesic distances relative error (knn connectivity) = {}%'.
      format(dijkstra_relative_error))

# Computing PTU distances with triangulation connectivity
print('Computing PTU dists with triangulation connectivity')
ptu = PTU.with_custom_graph(X=X,
                            graph=T,
                            geod_n_neighbors=10,
                            embedding_dim=2,
                            verbose=True)
ptu.compute_geodesic_distances()
ptu_dists = ptu.ptu_dists
def approximate_image(image_name, writer, results_dict):
    image_path = image_prefix + image_name

    image = cv2.imread(image_path)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    # image = cv2.resize(image, (512, 512))
    image = cv2.normalize(image,
                          image,
                          alpha=0,
                          beta=1,
                          norm_type=cv2.NORM_MINMAX,
                          dtype=cv2.CV_32F)

    results_dict["Shape"] = image.shape
    results_dict["Data"] = image_name

    for real_rank in real_ranks:
        path_prefix = results_prefix + image_name[:-5] + "__" + str(
            real_rank) + "_"
        low_rank_image = utils.low_rank_approximation(image, real_rank)

        if write:
            cv2.imwrite(path_prefix + "low_rank.png",
                        normalize(low_rank_image))

        for density in densities:
            mask = np.random.choice([0, 1],
                                    image.shape,
                                    p=[1 - density, density])
            train_mask = np.random.choice([0, 1], image.shape, p=[0.2, 0.8
                                                                  ]) * mask
            test_mask = np.random.choice([0, 1], image.shape, p=[0.8, 0.2
                                                                 ]) * mask

            masked_image = train_mask * low_rank_image

            if write:
                masked_image_green = cv2.cvtColor(
                    masked_image.astype(np.float32), cv2.COLOR_GRAY2RGB)
                masked_image_green[:, :, 1][masked_image_green[:, :,
                                                               1] == 0] = 1.0
                cv2.imwrite(
                    path_prefix + str(int(100 * density)) + "_masked.png",
                    normalize(masked_image_green))

            for rank in ranks:
                result = minimize(masked_image,
                                  rank,
                                  train_mask,
                                  iter_max,
                                  norm_tol,
                                  verbose=verbose)

                results_dict["Train_error"] = utils.relative_error(
                    result.matrix, low_rank_image, train_mask)
                results_dict["Test_error"] = utils.relative_error(
                    result.matrix, low_rank_image, test_mask)
                results_dict["Full_error"] = utils.relative_error(
                    result.matrix, low_rank_image)
                results_dict["Relative_error"] = result.residual

                if (verbose):
                    print("Train error:", results_dict["Train_error"])
                    print("Test error:", results_dict["Test_error"])
                    print("Full error:", results_dict["Full_error"])
                    print("Relative error:", results_dict["Relative_error"])

                add_result(writer, results_dict, result, density, real_rank,
                           rank)

                if write:
                    result_matrix = cv2.cvtColor(
                        result.matrix.astype(np.float32), cv2.COLOR_GRAY2RGB)

                    if labels:
                        font = cv2.FONT_HERSHEY_COMPLEX_SMALL
                        label_text = "Rank: " + str(rank) + "   Error: " + str(
                            round(results_dict["Test_error"], 3))
                        cv2.putText(result_matrix, label_text, (200, 500),
                                    font, 1, (0, 0, 255), 2, cv2.LINE_AA)

                    cv2.imwrite(
                        path_prefix + str(rank) + "_" +
                        str(int(100 * density)) + "_approx.png",
                        normalize(np.clip(result_matrix, 0, 1)))
def main():
    if len(sys.argv) > 1:
        algorithm = sys.argv[1]
    else:
        algorithm = "ASD"

    image = cv2.imread("../Data/Images/pexels-photo-688018.jpeg")
    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    image = cv2.normalize(image,
                          image,
                          alpha=0,
                          beta=1,
                          norm_type=cv2.NORM_MINMAX,
                          dtype=cv2.CV_32F)

    # Cambiar tamaño
    image = cv2.resize(image, (512, 512))
    m, n = image.shape

    # Aproximación de rango bajo
    rank = 50
    low_rank_image = utils.low_rank_approximation(image, rank)

    # Máscara
    density = 0.3
    mask = np.random.choice([0, 1], (m, n), p=[1 - density, density])
    masked_image = mask * low_rank_image

    # Optimizar
    iter_max = 20000
    norm_tol = 1e-4

    if algorithm == "sASD":
        minimize = ASD.scaled_alternating_steepest_descent
        result = minimize(masked_image, rank, mask, iter_max, norm_tol)
        asd_image = result.matrix
    else:  # algorithm == "ASD":
        minimize = ASD.alternating_steepest_descent
        result = minimize(masked_image, rank, mask, iter_max, norm_tol)

    masked_image = cv2.cvtColor(masked_image.astype(np.float32),
                                cv2.COLOR_GRAY2RGB)
    masked_image[:, :, 1][masked_image[:, :, 1] == 0] = 1.0

    path_prefix = "../Results/Noisy_Images/"

    # Calcular error con imagen original
    print("Error relativo", utils.relative_error(asd_image, image))

    # Normalizar imagenes
    normalize = functools.partial(cv2.normalize,
                                  dst=None,
                                  alpha=0,
                                  beta=255,
                                  norm_type=cv2.NORM_MINMAX,
                                  dtype=cv2.CV_8U)
    image = normalize(image)
    low_rank_image = normalize(low_rank_image)
    mask = normalize(mask)
    masked_image = normalize(masked_image)
    asd_image = normalize(asd_image)

    # Mostrar resultados
    cv2.imshow("masked", masked_image)
    cv2.imshow(algorithm, asd_image)
    cv2.waitKey()

    # Guardar resultados
    cv2.imwrite(path_prefix + "image.png", image)
    cv2.imwrite(path_prefix + "mask.png", mask)
    cv2.imwrite(path_prefix + "low_rank.png", low_rank_image)
    cv2.imwrite(path_prefix + "masked.png", masked_image)
    cv2.imwrite(path_prefix + algorithm + ".png", asd_image)