1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| import numpy as np from PIL import Image import matplotlib.pyplot as plt import pylab
def loadImage(filename): image = Image.open(filename) return np.array(image)
def svd(A): return np.linalg.svd(A)
def reBuildSVD(U, S, V): r = len(S) return np.dot(U[:,:r] * S, V[:r,:])
def setZero(U, S, V, k): r = len(S) for i in range(k, r): U[:, i] = 0 S[i] = 0 V[i, :] = 0 return U, S, V
def totalVariation(S, k): return np.sum(S[:k]) / np.sum(S)
def imageProcess(img, k): img2 = np.zeros_like(img) tv = 1.0 for c in range(img.shape[2]): A = img[:, :, c] U, S, V = svd(A) tv *= totalVariation(S, k) U, S, V = setZero(U, S, V, k) img2[:, :, c] = reBuildSVD(U, S, V) return img2, tv
def Ratio(A, k): den = A.shape[0] * A.shape[1] * A.shape[2] nom = (A.shape[0] * k + k * A.shape[1] + k) * A.shape[2] return 1 - nom/den
filname = "./miku.jpg" miku = loadImage(filname)
plt.figure(figsize=(20, 10))
plt.subplot(2, 2, 1) plt.imshow(miku) plt.title("origin")
plt.subplot(2, 2, 2) img, var = imageProcess(miku, 4 ** 2) ratio = Ratio(miku, 4 ** 1) plt.imshow(img) plt.title('{:.2%} / {:.2%}'.format(var, ratio))
plt.subplot(2, 2, 3) img, var = imageProcess(miku, 4 ** 3) ratio = Ratio(miku, 4 ** 3) plt.imshow(img) plt.title('{:.2%} / {:.2%}'.format(var, ratio))
plt.subplot(2, 2, 4) img, var = imageProcess(miku, 4 ** 4) ratio = Ratio(miku, 4 ** 4) plt.imshow(img) plt.title('{:.2%} / {:.2%}'.format(var, ratio))
pylab.show()
|