希伯特曲线具体干什么的,就不多说了,直接上代码!
class Hilbert:
# n 行列数
def __init__(self, n ):
self.n = n
def rot(self, xy, rx, ry):
n = self.n
if ry == 0:
if rx == 1:
xy[0] = n - 1 - xy[0]
xy[1] = n - 1 - xy[1]
temp = xy[0]
xy[0] = xy[1]
xy[1] = temp
return
def he_to_xy(self, d, xy): # 返回hilbert数值对应的二维坐标
n = self.n
t = d
xy[0] = xy[1] = 0
s = 1
while s < n:
rx = int(1 & int(t / 2))
ry = int(1 & (int(t) ^ rx))
self.rot(xy, rx, ry)
xy[0] += s * rx
xy[1] += s * ry
t /= 4
s *= 2
return xy[1], xy[0]
def xy_to_he(self, xy): # 返回二维坐标h对应的hilbert数值
n = self.n
d = 0
s = n / 2
while s > 0:
if (int(xy[0]) & int(s)) > 0:
rx = 1
else:
rx = 0
if (int(xy[1]) & int(s)) > 0:
ry = 1
else:
ry = 0
d += s * s * ((3 * rx) ^ ry)
self.rot(xy, rx, ry)
s /= 2
return d
#=========================== 测试 8x8 的 生成结果 ============================
n = 8
xy = [0, 0]
hi = Hilbert(n)
for i in range(0,n):
for j in range(0,n):
xy[0] = j
xy[1] = i
print("%4d"% int(hi.xy2d(xy)), end='')
print()
#=========================== 测试 相互转换 ============================
xy1 = [1, 2] # i j 相反
print(hi.xy_to_he(xy1))
print(hi. he_to_xy(4, xy))
结果
0 3 4 5 58 59 60 63
1 2 7 6 57 56 61 62
14 13 8 9 54 55 50 49
15 12 11 10 53 52 51 48
16 17 30 31 32 33 46 47
19 18 29 28 35 34 45 44
20 23 24 27 36 39 40 43
21 22 25 26 37 38 41 42
13.0
(0, 2)