1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| import numpy as np from PIL import Image
if __name__ == "__main__":
Img = Image.open('./test.jpg') Img_array = np.array(Img) A = Img_array[:,:,0] A_T = A.transpose() A_TA = np.dot(A_T, A)
eigenvalues,eigenVectors = np.linalg.eig(A_TA) tmp = np.column_stack((eigenvalues, eigenVectors)) tmp = tmp[np.argsort(-(tmp[:,0]))] singularValues, singularVectorsV = np.nan_to_num(np.power(tmp[:, 0], 0.5)), tmp[:, 1:]
singularVectorsU = np.dot(A, singularVectorsV)/singularValues
threshold = 0.99 SigmaSum = np.sum(singularValues) tmp = singularValues[0] i = 1 while(tmp/SigmaSum <= threshold): tmp += singularValues[i] i += 1
reConstructImgArray = np.dot( np.dot(singularVectorsU[:, 0:i+1], np.diag(singularValues[0:i+1])), np.transpose(singularVectorsV[:, 0:i+1]))
reConstructImg = Image.fromarray(reConstructImgArray) reConstructImg.show() print("good luck")
|