-
Notifications
You must be signed in to change notification settings - Fork 0
/
zigzag2D.py
37 lines (32 loc) · 927 Bytes
/
zigzag2D.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
import numpy as np
def scan(v, h, i, vmax, hmax):
i += 1
if (h + v) % 2 == 0:
if v == 0 and h < hmax - 1: h += 1
elif h == hmax - 1: v += 1
else: v -= 1; h += 1
else:
if v == vmax - 1: h += 1
elif h == 0: v += 1
else: v += 1; h -= 1
return v, h, i
def zigzag(x):
v, h, i = 0, 0, 0
vmax, hmax = x.shape
y = np.zeros(vmax * hmax).astype(x.dtype)
while v < vmax and h < hmax:
y[i] = x[v, h]
v, h, i = scan(v, h, i, vmax, hmax)
return y[:i]
def inverse_zigzag(y, vmax, hmax):
v, h, i = 0, 0, 0
x = np.zeros((vmax, hmax)).astype(y.dtype)
while v < vmax and h < hmax:
x[v, h] = y[i]
v, h, i = scan(v, h, i, vmax, hmax)
return x
input_tensor = np.arange(64).reshape((8, 8))
output = zigzag(input_tensor)
print(output)
reconstructed_tensor = inverse_zigzag(output, 8, 8)
print(reconstructed_tensor)