def show_reconstruction(n_training_img=5): """ Show the images corresponding to the reconstruction process, namely: - Original face - Mean image - Eigenfaces - Reconstructed face """ train_img, train_labels, test_img, test_labels = load_images( n_training_img) nearest_neighbor = NN() nearest_neighbor.train(train_img, train_labels, 10) face_idx = np.random.randint(0, len(train_labels)) plt.imshow(shape_image(train_img[face_idx]), cmap="gray") plt.title("Original face") plt.axis('off') plt.figure() eigenfaces = np.zeros(nearest_neighbor.eigenfaces.shape) for i in range(nearest_neighbor.eigenfaces.shape[1]): eigenfaces[:, i] = nearest_neighbor.face_space_coord_train[ face_idx] * nearest_neighbor.eigenfaces[:, i] plt.imshow(shape_image(nearest_neighbor.mean_face), cmap="gray") plt.title("Mean face") plt.axis('off') plt.figure() for i, eigenface in enumerate(eigenfaces): plt.subplot(1, eigenfaces.shape[0], i + 1) plt.imshow(shape_image(eigenface), cmap="gray") plt.axis('off') plt.subplots_adjust(wspace=0, hspace=0) plt.suptitle("Eigenfaces") plt.figure() plt.imshow(shape_image( nearest_neighbor.get_reconstructed_faces(train_img)[face_idx]), cmap='gray') plt.title("Reconstructed image") plt.axis('off') plt.show()
def show_reconstructed(n_training_img, k_ppal_components, n_images): """ Show side by side the original image and the reconstruction using different number of principal components (eigenfaces) :param n_training_img: Number of training images used per person :param k_ppal_components: Array with the number of eigenfaces to use :param n_images: Number of images of people to show """ train_img, train_labels, test_img, test_labels = load_images( n_training_img) # Randomize the selection of faces to show face_ids = [i for i in range(len(train_labels))] np.random.shuffle(face_ids) # Reconstruct the images from the training data reconstructed = [] for n_k in k_ppal_components: nearest_neighbor = NN() nearest_neighbor.train(train_img, train_labels, n_k) reconstructed.append( nearest_neighbor.get_reconstructed_faces(train_img)) # Plot the results fig, axarr = plt.subplots(n_images, 1 + len(k_ppal_components)) axarr[0, 0].set_title("Original") for j, n_k in enumerate(k_ppal_components): axarr[0, j + 1].set_title("K = " + str(n_k)) for i in range(n_images): face_id = face_ids[i] axarr[i, 0].imshow(shape_image(train_img[face_id]), cmap="gray") axarr[i, 0].axis('off') for j, n_k in enumerate(k_ppal_components): axarr[i, j + 1].imshow(shape_image(reconstructed[j][face_id]), cmap="gray") axarr[i, j + 1].axis('off') plt.subplots_adjust(wspace=0, hspace=0) fig.suptitle(f'Reconstruction analysis. {n_training_img} training images') plt.show()