import numpy as np import matplotlib.pyplot as plt# from PIL import Image import requests inha = Image.open(requests.get("https://jonghank.github.io/ase7030/files/SymbolMark.jpg", stream=True).raw) inha = np.array(inha)/255. plt.figure(figsize=(8,8), dpi=100) plt.imshow(inha) plt.axis('off') plt.title('Raw color image') plt.show() R_channel = inha[:,:,0] G_channel = inha[:,:,1] B_channel = inha[:,:,2] X = 0.299*R_channel + 0.587*G_channel + 0.114*B_channel m, n = X.shape print(m,n) plt.figure(figsize=(8,8), dpi=100) plt.imshow(X, cmap='gray', vmin=0, vmax=1) plt.title(f'Grayscale image ({m*n} real numbers)') plt.axis('off') plt.show() U,S,Vt = np.linalg.svd(X) plt.figure(figsize=(14,8), dpi=100) plt.subplot(121) plt.plot(S) plt.grid() plt.xlabel('Index') plt.ylabel('Singular values') plt.subplot(122) plt.semilogy(S) plt.grid() plt.xlabel('Index') plt.ylabel('Singular values') plt.show() plt.figure(figsize=(8,8), dpi=100) plt.imshow(X, cmap='gray', vmin=0, vmax=1) plt.axis('off') plt.title(f'Original image ({m*n} real numbers)') plt.show() for k in [2,5,10,20,40,60,80]: plt.figure(figsize=(8,8), dpi=100) X_compressed = U[:,:k]@np.diag(S[:k])@Vt[:k,:] plt.imshow(X_compressed, cmap='gray', vmin=0, vmax=1) plt.title(f'Compressed image ({(m+n+1)*k} real numbers), rank {k}') plt.axis('off') plt.show()