Skip to content

Instantly share code, notes, and snippets.

@AtomicVar
Created March 15, 2019 12:53
Show Gist options
  • Save AtomicVar/498a4df84d32b7e7cf9410e36169d860 to your computer and use it in GitHub Desktop.
Save AtomicVar/498a4df84d32b7e7cf9410e36169d860 to your computer and use it in GitHub Desktop.
Python图片压缩:使用奇异值分解
from scipy.misc import imread
from scipy.linalg import svd
import matplotlib.pyplot as plt
import numpy as np
if __name__ == '__main__':
img = imread('mm.jpg')
h, w, c = img.shape
U0, S0, V0 = svd(img[:, :, 0])
U1, S1, V1 = svd(img[:, :, 1])
U2, S2, V2 = svd(img[:, :, 2])
S0 = np.diag(S0)
S1 = np.diag(S1)
S2 = np.diag(S2)
c0 = (U0[:, :20] @ S0[:20, :20] @ V0[:20, :]).reshape(h, w, 1)
c1 = (U1[:, :20] @ S1[:20, :20] @ V1[:20, :]).reshape(h, w, 1)
c2 = (U2[:, :20] @ S2[:20, :20] @ V2[:20, :]).reshape(h, w, 1)
new_img = np.concatenate((c0, c1, c2), axis=2)
plt.imshow(np.uint8(new_img))
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment