V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
爱意满满的作品展示区。
mathzhaoliang
V2EX  ›  分享创造

用 Python 制作演示 Hilbert 曲线的 gif 动图

  •  
  •   mathzhaoliang ·
    neozhaoliang · 2018-11-20 14:20:38 +08:00 · 1659 次点击
    这是一个创建于 1982 天前的主题,其中的信息可能已经有所发展或是发生改变。

    下图演示的是一个二维的、阶为 n=6 的 Hilbert 分形曲线:

    Hilbert 曲线上包含 2^n x 2^n 个不同的点,这些点与 Golay 码一一对应。这个曲线就是利用 Golay 码生成的。

    这个图片是用纯 python 生成的,运行时间正好是 1 秒整 (在我的 dell 7050 台式机上)。

    代码点这里:

    https://github.com/neozhaoliang/pywonderland/blob/master/src/gifmaze/example_hilbert_curve.py

    SeaRecluse
        1
    SeaRecluse  
       2018-11-20 17:19:54 +08:00
    看上去不错,抛砖引玉下

    ```python
    import matplotlib.pyplot as plt
    import numpy as np
    from matplotlib.animation import FuncAnimation

    #-----------------------------坐标转换----------------------------
    def rot(n,x,y,rx,ry):
    if ry == 0:
    if rx == 1:
    x = (n - 1 - x)
    y = (n - 1 - y)

    tmp = x
    x = y
    y = tmp

    return x,y

    def xy2d(n,x,y):
    rx,ry,s,d = 0,0,0,0
    s = n//2
    while s:
    rx = 1 if (x&s) > 0 else 0
    ry = 1 if (y&s) > 0 else 0
    d += s * s * ((3 * rx) ^ ry)
    x,y = rot(s,x,y,rx,ry)
    s = s//2

    return d
    #-----------------------------n:2 的次幂----------------------------
    n = pow(2,4)
    x = np.arange(0,n)
    y = np.arange(0,n)

    allxy = []
    for per_y in y:
    for per_x in x:
    d = xy2d(n,per_x,per_y)
    allxy.append([per_x,per_y,d])

    for i in range(len(allxy)):
    for j in range(i + 1, len(allxy)):
    if allxy[j][2] < allxy[i][2]:
    temp = allxy[j]
    allxy[j] = allxy[i]
    allxy[i] = temp
    #-----------------------------画动态图----------------------------
    fig, ax = plt.subplots()
    xdata, ydata = [], []
    ln, = ax.plot([], [], '-*', color = "purple", animated=False)

    def init():
    ax.set_xlim(-0.25, n-0.25)
    ax.set_ylim(-0.25, n-0.25)
    return ln,

    def update(frame):
    xdata.append(allxy[frame][0])
    ydata.append(allxy[frame][1])
    lnT, = ax.plot([], [], '-*', animated=False)
    lnT.set_data(xdata[-2:], ydata[-2:])
    ln.set_data(xdata[:-1], ydata[:-1])
    return ln,lnT

    ani = FuncAnimation(fig, update, frames=range(0,pow(n,2)),
    init_func=init, blit=True)

    plt.show()
    #-----------------------------画静态图----------------------------
    # allxy = np.array(allxy)
    # plt.figure()
    # plt.plot(allxy[:,0],allxy[:,1],'-*',color = "purple",linewidth=2)
    # plt.show()
    ```
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3931 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 10:24 · PVG 18:24 · LAX 03:24 · JFK 06:24
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.