import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg import sys orig = mpimg.imread(sys.argv[1]) def rgb2gray(rgb): return np.dot(rgb[...,:3], [0.299, 0.587, 0.114]) gray = rgb2gray(orig) def plot_image(im): plt.imshow(im, cmap = plt.get_cmap('gray')) plt.show() def get_PCA(M, r): u, s, vh = np.linalg.svd(M) U=np.transpose(np.transpose(u)[0:r]) Vh=vh[0:r] S=np.diag(s[0:r]) projection = np.matrix(U)*np.matrix(S)*np.matrix(Vh) return projection if sys.argv[2]=='p': print(str(len(gray))+'x'+str(len(gray[1]))) plot_image(gray) else: plot_image(get_PCA(gray, int(sys.argv[2])))