图像压缩 Python 奇异值分解(学习笔记)

  • Post author:
  • Post category:python

import numpy as np
import matplotlib.pyplot as plt
def svdimage(filename,percent):
    original=plt.imread(filename)
    R0=np.array(original[:,:,0])
    G0=np.array(original[:,:,1])
    B0=np.array(original[:,:,2])
    u0,sigma0,v0=np.linalg.svd(R0)
    u1,sigma1,v1=np.linalg.svd(G0)
    u2,sigma2,v2=np.linalg.svd(B0)
    R1=np.zeros(R0.shape)
    G1=np.zeros(G0.shape)
    B1=np.zeros(B0.shape)
    total0=sum(sigma0)
    total1=sum(sigma1)
    total2=sum(sigma2)
    #用奇异值总和的百分比进行筛选
    sd=0
    for i,sigma in enumerate(sigma0):
        R1+=sigma*np.dot(u0[:,i].reshape(-1,1),v0[i,:].reshape(1,-1))#reshape(-1,1)纵向展开,reshape(1,-1)横向展开
        sd+=sigma
        if sd>=percent*total0:
            break
    sd=0
    for i,sigma in enumerate(sigma1):
        G1+=sigma*np.dot(u1[:,i].reshape(-1,1),v1[i,:].reshape(1,-1))
        sd+=sigma
        if sd>=percent*total1:
            break
    sd=0
    for i,sigma in enumerate(sigma2):
        B1+=sigma*np.dot(u2[:,i].reshape(-1,1),v2[i,:].reshape(1,-1))
        sd+=sigma
        if sd>=percent*total2:
            break
    final=np.stack((R1,G1,B1),2)
    final[final>255]=255
    final[final<0]=0
    final=np.rint(final).astype('uint8')#np.rint()四舍五入取整
    return final

filename='/example.jpg'
for p in np.arange(0.1,1,0.1):
    after=svdimage(filename,p)
    plt.imsave('/'+str(p)+'_1.jpg',after)

保留奇异值50%的压缩信息的图像
在这里插入图片描述
保留奇异值90%的压缩信息的图像
在这里插入图片描述


版权声明:本文为weixin_44819497原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。