-
Notifications
You must be signed in to change notification settings - Fork 0
/
compression.py
111 lines (72 loc) · 1.93 KB
/
compression.py
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import numpy as np
def write_as_mcf(ndarray, filename):
file = open(filename + ".mcf", "wb")
file.write(ndarray.tobytes())
def read_as_np(filename: np.ndarray):
nparray = np.fromfile(filename + ".mcf", dtype=np.uint8)
return nparray
def lzw_compress(image: np.ndarray) -> np.ndarray:
di_limit = 512
di = [[i] for i in range(256)]
w = []
result = []
for p in image:
wc = w + [p]
if wc in di:
print(wc)
w = wc
else:
result.append(di.index(w))
if len(di) < di_limit:
di += [w]
print(w)
w += [p]
if w:
result.append(di.index(w))
return np.array(result)
def lzw_decompress(vec: np.ndarray):
compressed: list = vec.tolist()
di = [[i] for i in range(256)]
w = compressed.pop()
result = [w]
for k in compressed:
print(k)
if [k] in di:
entry = di[k]
elif k == len(di):
entry = [k] + di[0]
else:
raise ValueError("It is not possible to decompress the file")
result += entry
di += [[w] + [entry[0]]]
w = entry
return np.array(result)
def run_length(vec: np.ndarray):
run = []
i = 0
while i < vec.size:
count = 0
for j in range(i, vec.size):
if vec[i] == vec[j]:
count += 1
else:
break
run += [count, vec[i]]
i += count
return np.array(run)
def run_length_inv(run: np.ndarray):
vec = []
for i in range(0, run.size, 2):
for j in range(run[i]):
vec += [run[i+1]]
return np.array(vec)
def compress(image):
shape = image.shape
img_vect = image.reshape(image.size)
r = run_length(img_vect)
print(r.shape)
return r
def decompress(vec, shape):
dr = run_length_inv(vec)
img = dr.reshape(shape)
return img