In [43]:
# System imports
import numpy as np
import math
class Jpeg:
PI_DIV_16 = math.pi / 16
INV_SQRT_2 = 1 / math.sqrt(2)
def __init__(self, number_of_cells, quantisation_matrix):
self.number_of_cells = number_of_cells
self.quantisation_matrix = quantisation_matrix
self.output = np.zeros(shape=(self.number_of_cells, self.number_of_cells))
self.compression_factor = 0
def compress(self, input_, compression_factor):
self.compression_factor = compression_factor
for u in range(0, self.number_of_cells):
cu = self.INV_SQRT_2 if u == 0 else 1
for v in range(0, self.number_of_cells):
cv = self.INV_SQRT_2 if v == 0 else 1
sum_ = 0
for x in range(0, self.number_of_cells):
cos1 = math.cos(self.PI_DIV_16 * u * (2 * x + 1))
for y in range(0, self.number_of_cells):
cos2 = math.cos(self.PI_DIV_16 * v * (2 * y + 1))
sum_ = sum_ + input_[x, y] * cos1 * cos2
sum_ = self.compression_factor * cu * cv * sum_ / self.quantisation_matrix[u, v]
self.output[u, v] = sum_
return self.output
def decompress(self, input_):
# Clear output matrix
self.output = np.zeros(shape=(self.number_of_cells, self.number_of_cells))
for x in range(0, self.number_of_cells):
for y in range(0, self.number_of_cells):
sum_ = 0
for u in range(0, self.number_of_cells):
cu = self.INV_SQRT_2 if u == 0 else 1
cos1 = math.cos(self.PI_DIV_16 * u * (2 * x + 1))
for v in range(0, self.number_of_cells):
cv = self.INV_SQRT_2 if v == 0 else 1
cos2 = math.cos(self.PI_DIV_16 * v * (2 * x + 1))
sum_ = sum_ + cu * cv * input_[u, v] * cos1 * cos2 * self.quantisation_matrix[u, v]
sum_ = sum_ * self.compression_factor
self.output[x, y] = sum_
return self.output
In [45]:
import scipy.misc as misc
import matplotlib.pyplot as plt
source_matrix = np.matrix(
'100 100 100 100 100 100 100 100 ;'
'100 100 100 100 100 100 100 100 ;'
'100 100 100 100 100 100 100 100 ;'
'100 100 100 100 100 100 100 100 ;'
'0 0 0 0 0 0 0 0 ;'
'0 0 0 0 0 0 0 0 ;'
'0 0 0 0 0 0 0 0 ;'
'0 0 0 0 0 0 0 0'
)
quantisation_matrix = np.matrix(
'16 11 10 16 24 40 51 61 ;'
'12 12 14 19 26 58 60 55 ;'
'14 13 16 24 40 57 69 56 ;'
'14 17 22 29 51 87 80 62 ;'
'18 22 37 56 68 109 103 77 ;'
'24 35 55 64 81 104 113 92 ;'
'49 64 78 87 103 121 120 101 ;'
'72 92 95 98 112 100 103 99'
)
jpeg = Jpeg(8, quantisation_matrix)
output = jpeg.compress(source_matrix, 1)
output_reconstructed = jpeg.decompress(output)
plt.imshow(source_matrix)
plt.title('Source matrix (weird colors..)')
plt.show()
plt.imshow(output)
plt.title('Ouput of compression')
plt.show()
plt.imshow(output_reconstructed)
plt.title('Ouput after reconstruction')
plt.show()
In [ ]:
0