In [24]:
import numpy as np
import matplotlib.pyplot as plt
from scipy import fftpack
from scipy.misc import bytescale
import matplotlib.image as mpimg
In [25]:
# loading a simple Z character image (8x8)
img = bytescale(mpimg.imread('i/z_char_8x8.png'))
img_h = 8
gray_img = img[:,:,0]
plt.imshow(img, cmap='gray', interpolation='nearest')
Out[25]:
In [26]:
np.set_printoptions(precision=1, linewidth=140, suppress=True)
gray_img
Out[26]:
In [27]:
# transform: 2D DCT
z_dct = fftpack.dct(fftpack.dct(gray_img.T, norm='ortho').T, norm='ortho')
np.set_printoptions(precision=1, linewidth=140, suppress=True)
z_dct
Out[27]:
In [28]:
dct_basis = bytescale(mpimg.imread('i/dct_basis.png'))
plt.imshow(dct_basis, cmap='gray', interpolation='nearest')
Out[28]:
In [29]:
partial_z_idct = []
partial_z_dct = []
for ii in range(img_h*img_h):
dct_copy = np.copy(z_dct)
frequency_counter = 0
for u in range(img_h):
for v in range(img_h):
if frequency_counter > ii:
dct_copy[u,v] = 0
frequency_counter += 1
partial_z_dct.append(dct_copy)
partial_img_idct = fftpack.idct(fftpack.idct(dct_copy.T, norm='ortho').T, norm='ortho')
partial_z_idct.append(partial_img_idct)
In [30]:
# shows each coefficient evolution towards the image formation
# here you can see how each DCT basis constributes to the image formation
# try to visualize them as a summation of the basis throughout the 64 elements
fig = plt.figure(figsize=(16, 16))
for ii in range(img_h*img_h):
plt.subplot(8, 8, ii + 1)
plt.title(partial_z_dct[ii][int(ii / 8), ii % 8])
plt.imshow(partial_z_idct[ii], cmap='gray', interpolation='nearest')
plt.grid(False);
plt.xticks([]);
plt.yticks([]);