首页 » 机器学习实战 » 机器学习实战全文在线阅读

《机器学习实战》14.6 示例:基于SVD的图像压缩

关灯直达底部

在本节中,我们将会了解一个很好的关于如何将SVD应用于图像压缩的例子。通过可视化的方式,该例子使得我们很容易就能看到SVD对数据近似的效果。在代码库中,我们包含了一张手写的数字图像,该图像在第2章使用过。原始的图像大小是32×32=1024像素,我们能否使用更少的像素来表示这张图呢?如果能对图像进行压缩,那么就可以节省空间或带宽开销了。

我们可以使用SVD来对数据降维,从而实现图像的压缩。下面我们就会看到利用SVD的手写数字图像的压缩过程了。在下面的程序清单中包含了数字的读入和压缩的代码。要了解最后的压缩效果,我们对压缩后的图像进行了重构。打开svdRec.py文件并加入如下代码。

程序清单14-4 图像压缩函数

def printMat(inMat, thresh=0.8):    for i in range(32):        for k in range(32):            if float(inMat[i,k]) > thresh:                print 1,            else: print 0,        print /'/'def imgCompress(numSV=3, thresh=0.8):    myl =     for line in open(/'0_5.txt/').readlines:        newRow =         for i in range(32):            newRow.append(int(line[i]))        myl.append(newRow)    myMat = mat(myl)    print /"****original matrix******/"    printMat(myMat, thresh)    U,Sigma,VT = la.svd(myMat)    SigRecon = mat(zeros((numSV, numSV)))    for k in range(numSV):        SigRecon[k,k] = Sigma[k]    reconMat = U[:,:numSV]*SigRecon*VT[:numSV,:]    print /"****reconstructed matrix using %d singular values******/" % numSV    printMat(reconMat, thresh)  

上述程序中第一个函数printMat的作用是打印矩阵。由于矩阵包含了浮点数,因此必须定义浅色和深色。这里通过一个阈值来界定,后面也可以调节该值。该函数遍历所有的矩阵元素,当元素大于阈值时打印1,否则打印0。

下一个函数实现了图像的压缩。它允许基于任意给定的奇异值数目来重构图像。该函数构建了一个列表,然后打开文本文件,并从文件中以数值方式读入字符。在矩阵调入之后,我们就可以在屏幕上输出该矩阵了。接下来就开始对原始图像进行SVD分解并重构图像。在程序中,通过将Sigma重新构成SigRecon来实现这一点。Sigma是一个对角矩阵,因此需要建立一个全0矩阵,然后将前面的那些奇异值填充到对角线上。最后,通过截断的UVT矩阵,用SigRecon得到重构后的矩阵,该矩阵通过printMat函数输出。

下面看看该函数的运行效果:

>>> reload(svdRec)<module /'svdRec/' from /'svdRec.py/'>>>> svdRec.imgCompress(2)****original matrix******0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 00 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 00 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 00 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 00 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 00 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 00 0 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 00 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 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0 0 0 0 0 0 0 

可以看到,只需要两个奇异值就能相当精确地对图像实现重构。那么,我们到底需要多少个0-1的数字来重构图像呢?UVT都是32x2的矩阵,有两个奇异值。因此总数字数目是64+64+2=130。和原数目1024相比,我们获得了几乎10倍的压缩比。