In [6]:
import numpy as np
import matplotlib.pyplot as plt
from scipy import fftpack
from scipy.misc import bytescale
import matplotlib.image as mpimg
In [7]:
# loading image
img = bytescale(mpimg.imread('i/super_mario_head.png'))
choosen_y_x = 90
resolution = 128
img_slice = img[choosen_y_x:(choosen_y_x + resolution), choosen_y_x:(choosen_y_x + resolution), 2]
In [8]:
# transform: 2D DCT
dct_slice = fftpack.dct(fftpack.dct(img_slice.T, norm='ortho').T, norm='ortho')
dct_hist, dct_bin_edges = np.histogram(dct_slice, bins = range(100))
img_hist, img_bin_edges = np.histogram(img_slice, bins = range(100))
f, (plt1, plt2) = plt.subplots(1, 2, figsize=(15, 5))
plt1.set_title('Frequency histogram')
plt1.bar(dct_bin_edges[:-1], dct_hist, width = 1)
plt2.set_title('Spatial histogram')
plt2.bar(img_bin_edges[:-1], img_hist, width = 1)
Out[8]:
In [9]:
block = img_slice[80:88, 40:48]
quantize_step = 5
dct_slice = fftpack.dct(fftpack.dct(block.T, norm='ortho').T, norm='ortho')
dct_slice_quantized = np.divide(dct_slice,[quantize_step])
rounded_quantized = np.around(dct_slice_quantized)
dct_slice_requantized = np.multiply(rounded_quantized,[quantize_step])
idct_slice = fftpack.idct(fftpack.idct(dct_slice_requantized.T, norm='ortho').T, norm='ortho')
f, (plt1, plt2) = plt.subplots(1, 2, figsize=(15, 5))
plt1.axis('off');
plt1.set_title('Original')
plt1.imshow(block, cmap='gray',interpolation='nearest')
plt2.axis('off');
plt2.set_title('Quantized')
plt2.imshow(idct_slice, cmap='gray',interpolation='nearest')
Out[9]:
In [10]:
plt.imshow(dct_slice, interpolation='nearest', cmap=plt.cm.Paired)
plt.colorbar(shrink=1)
Out[10]:
In [11]:
# a 8x8 block
block = img_slice[80:88, 40:48]
# a 2D DCT
dct_slice = fftpack.dct(fftpack.dct(block.T, norm='ortho').T, norm='ortho')
original_dct_slice = np.copy(dct_slice)
# keeps only the top left 5 element triangle
for u in range(8):
for v in range(8):
if (u + v) > 5:
dct_slice[u, v] = 0
print("It compressed ", 100 - ((np.count_nonzero(dct_slice)/64) * 100), "% of the block.")
In [13]:
np.set_printoptions(precision=1, linewidth=140, suppress=True)
block
Out[13]:
In [14]:
original_dct_slice
Out[14]:
In [15]:
dct_slice
Out[15]:
In [16]:
idct_slice = fftpack.idct(fftpack.idct(dct_slice.T, norm='ortho').T, norm='ortho')
f, (plt1, plt2) = plt.subplots(1, 2, figsize=(15, 5))
plt1.axis('off');
plt1.set_title('Original')
plt1.imshow(block, cmap='gray', interpolation='nearest')
plt2.axis('off');
plt2.set_title('Quantized')
plt2.imshow(idct_slice, cmap='gray', interpolation='nearest')
Out[16]:
In [17]:
img = mpimg.imread('i/jpeg_quantization_table.png')
plt.axis('off');
plt.imshow(img)
Out[17]: