當前位置:首頁 > IT技術(shù) > 編程語言 > 正文

python 圖片SVD(奇異值分解)壓縮測試
2022-02-14 14:10:47


python圖片SVD(奇異值分解)壓縮測試

對圖片進行壓縮,使用SVD分解,取前%K 的權(quán)重值,對比壓縮前和壓縮后的模型精度。

# -*- coding: utf-8 -*-


from numpy import linalg as la
import matplotlib.pyplot as plt
from sklearn import datasets
from skimage import io
import numpy as np
def getImgAsMat(index):
ds = datasets.fetch_olivetti_faces()
return np.mat(ds.images[index])

def getImgAsMatFromFile(filename):
img = io.imread(filename, as_gray=True)
print(np.mat(img))
return np.mat(img)

def plotImg(imgMat):
plt.imshow(imgMat, cmap=plt.cm.gray)
plt.show()

def recoverBySVD(imgMat, k):
# singular value decomposition
print(imgMat)
U, s, V = la.svd(imgMat)
print('length = ',len(s))
# choose top k important singular values (or eigens)
Uk = U[:, 0:k]
Sk = np.diag(s[0:k])
Vk = V[0:k, :]
# recover the image
imgMat_new = Uk * Sk * Vk
return imgMat_new


# -------------------- main --------------------- #
A = getImgAsMatFromFile('C:/Users/LJ/Desktop/AI_Picture.png')
plotImg(A)
A_new = recoverBySVD(A, 100)
plotImg(A_new)

python 圖片SVD(奇異值分解)壓縮測試_desktop



本文摘自 :https://blog.51cto.com/u

開通會員,享受整站包年服務立即開通 >