-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompress.py
More file actions
81 lines (63 loc) · 2.43 KB
/
compress.py
File metadata and controls
81 lines (63 loc) · 2.43 KB
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
from zigzag import *
from huffman import *
import cv2
def compress(encoded_text, quantization):
new_tree = HuffmanTree()
bitstream = new_tree.decode(encoded_text)
print('a', bitstream)
QUANTIZATION_MAT = np.array([[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]])
# defining block size
block_size = 8
details = bitstream.split()
h = int(''.join(filter(str.isdigit, details[0])))
w = int(''.join(filter(str.isdigit, details[1])))
array = np.zeros(h*w).astype(int)
print("shape", details)
# some loop var initialisation
k = 0
i = 2
x = 0
j = 0
# This loop gives us reconstructed array of size of image
while k < array.shape[0]:
if(details[i] == '999'):
break
# This is imp! note that to get negative numbers in array check for - sign in string
if "-" not in details[i]:
array[k] = int(''.join(filter(str.isdigit, details[i])))
else:
array[k] = -1*int(''.join(filter(str.isdigit, details[i])))
if(i+3 < len(details)):
j = int(''.join(filter(str.isdigit, details[i+3])))
if j == 0:
k = k + 1
else:
k = k + j + 1
i = i + 2
array = np.reshape(array,(h,w))
# loop for constructing intensity matrix form frequency matrix (IDCT and all)
i = 0
j = 0
k = 0
# initialisation of compressed image
padded_img = np.zeros((h,w))
while i < h:
j = 0
while j < w:
temp_stream = array[i:i+8,j:j+8]
block = inverse_zigzag(temp_stream.flatten(), int(block_size),int(block_size))
de_quantized = np.multiply(block,QUANTIZATION_MAT)
padded_img[i:i+8,j:j+8] = cv2.idct(de_quantized*quantization)
j = j + 8
i = i + 8
# clamping to 8-bit max-min values
padded_img[padded_img > 255] = 255
padded_img[padded_img < 0] = 0
return np.uint8(padded_img)