|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
from PIL import Image
import os
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
def restore1(u, sigma, v, k):
m = len(u)
n = len(v)
a = np.zeros((m, n))
# 重构图像
a = np.dot(u[:, :k], np.diag(sigma[:k])).dot(v[:k, :])
# 上述语句等价于:
# for i in range(k):
# ui = u[:, i].reshape(m, 1)
# vi = v[i].reshape(1, n)
# a += sigma[i] * np.dot(ui, vi)
a[a < 0] = 0
a[a > 255] = 255
return np.rint(a).astype('uint8')
if __name__ == '__main__':
A = Image.open('lena.bmp')
print (A)
#将压缩重构后的图片放在Pic目录下
output_path = r'.\Pic2' # r表示不转义,.表示当前目录
if not os.path.exists(output_path):
os.mkdir(output_path)
a = np.array(A) #转换成矩阵
print (a.shape)
a_col = a[:, :, None]
print(a_col.shape)
K = 50
#由于是彩色图像,所以3通道。a的最内层数组为三个数,分别表示RGB,用来表示一个像素
u_r, sigma_r, v_r = np.linalg.svd(a_col[:, :,0])
u_g, sigma_g, v_g = np.linalg.svd(a_col[:, :,1])
u_b, sigma_b, v_b = np.linalg.svd(a_col[:, :,2])
plt.figure(facecolor = 'w', figsize = (10, 10))
mpl.rcParams['font.sans-serif'] = [u'simHei']
mpl.rcParams['axes.unicode_minus'] = False
for k in range(1, K + 1):
print (k)
R = restore1(u_r, sigma_r, v_r, k)
G = restore1(u_g, sigma_g, v_g, k)
B = restore1(u_g, sigma_g, v_g, k)
I = np.stack((R, G, B), axis = 2)
# 如果读入的图片是png
# Image.fromarray(I).save('%s\\svd_%d.png' % (output_path, k), 'png')
# 如果读入的图片是jpg
Image.fromarray(I).save('%s\\svd_%d.jpg' % (output_path, k), 'jpeg')
if k <= 12:
plt.subplot(3, 4, k)
plt.imshow(I)
plt.axis('off')
plt.title(u'奇异值个数:%d' % k)
plt.suptitle(u'SVD与图像分解', fontsize = 20)
plt.tight_layout(0.1, rect = (0, 0, 1, 0.92))
plt.show()
|
|