人生苦短,我用python

机器学习入门-降维实例-图片压缩

2017-07-15  本文已影响27人  雷小厮
# 读取图片
from PIL import Image
img = Image.open('cat.jpeg')
#转为数学矩阵
import numpy
imgary = numpy.array(img)
imgary = imgary/255
# 查看原始大小
original_bytes = imgary.nbytes
# 拆分红绿蓝三色矩阵
img_red = imgary[:,:,0]
img_green = imgary[:,:,1]
img_blue = imgary[:,:,2]
# 使用SVD分解矩阵
# from numpy.linalg import svd 
from scipy.linalg import svd
U_r,S_r,V_r = svd(img_red,full_matrices=True)
U_g,S_g,V_g = svd(img_green,full_matrices=True)
U_b,S_b,V_b = svd(img_blue,full_matrices=True)
# 压缩图片
k=100
U_r_k = U_r[:,0:k]
S_r_k = S_r[0:k]
V_r_k = V_r[0:k,:]
U_g_k = U_g[:,0:k]
S_g_k = S_g[0:k]
V_g_k = V_g[0:k,:]
U_b_k = U_b[:,0:k]
S_b_k = S_b[0:k]
V_b_k = V_b[0:k,:]
# 查看压缩比例
compressed_bytes = sum([matrix.nbytes for matrix in [U_r_k,S_r_k,V_r_k,U_g_k,S_g_k,V_g_k,U_b_k,S_b_k,V_b_k]])
ratio = compressed_bytes/original_bytes
print(ratio)
# 还原矩阵
import numpy as np
image_red_approx = np.dot(U_r_k,np.dot(numpy.diag(S_r_k),V_r_k))
image_green_approx = np.dot(U_g_k,np.dot(numpy.diag(S_g_k),V_g_k))
image_blue_approx = np.dot(U_b_k,np.dot(numpy.diag(S_b_k),V_b_k))
row,col,_ = imgary.shape
img_reconstructed = np.zeros((row,col,3))
img_reconstructed[:,:,0] = image_red_approx
img_reconstructed[:,:,1] = image_green_approx
img_reconstructed[:,:,2] = image_blue_approx
img_reconstructed[img_reconstructed <0] = 0 # 异常值正规化
img_reconstructed[img_reconstructed >1] = 1 # 异常值正规化
# 查看压缩后图片
from matplotlib import pyplot as plt
fig = plt.figure(figsize=(10,10))
a  = fig.add_subplot(1,1,1)
plt.imshow(img_reconstructed)
# 保存压缩后图片
img_recon = img_reconstructed*255
img_recon.astype('uint8')
img2 = Image.fromarray(np.uint8(img_recon))
img2.save('newcat.jpg')
上一篇下一篇

猜你喜欢

热点阅读