用Numpy转换为网络墨卡托

2024-06-16 09:38:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我的程序垂直地扩展一个Numpy数组,表示一个180×360的地图图像,因此它表示一个webmercator地图图像。在

我写了一个函数(如下)来做我想做的-但是它非常慢(大约需要五分钟)。有没有一种更快更简单的方法?可能使用Numpyinterpolate2d或MatPlotLib?在

def row2lat(row):
  return 180.0/math.pi*(2.0*math.atan(math.exp(row*math.pi/180.0))-math.pi/2.0)

def mercator(geodetic):
    geo = np.repeat(geodetic, 2, axis=0)
    merc = np.zeros_like(geo)
    side = geo[0].size
    for row in range(side):
        lat = row2lat(180 - ((row * 1.0)/side) * 360)
        g_row = (abs(90 - lat)/180)*side
        fraction = g_row-math.floor(g_row)
        for col in range(side):
            high_row = geo[math.floor(g_row)][col] * (fraction)
            low_row = geo[math.ceil(g_row)][col] * (1-fraction)
            merc[row][col] = high_row + low_row
    return merc

OriginalFinal


Tags: 图像returndefnp地图picolmath
1条回答
网友
1楼 · 发布于 2024-06-16 09:38:27

尽量避免内部for循环并将函数矢量化。Numpy经过高度优化,可以高效地运行这些东西。你的函数应该是

def mercator_faster(geodetic):
    geo = np.repeat(geodetic, 2, axis=0)
    merc = np.zeros_like(geo)
    side = geo[0].size
    for row in range(side):
        lat = row2lat(180 - ((row * 1.0)/side) * 360)
        g_row = (abs(90 - lat)/180)*side
        fraction = g_row-math.floor(g_row)

        # Here I optimized the code by using the numpy vector operations 
        # instead of the for loop:

        high_row = geo[math.floor(g_row), :] * (fraction)
        low_row = geo[math.ceil(g_row), :] * (1-fraction)
        merc[row, :] = high_row + low_row

    return merc

如果我在我的机器上运行它只需要不到一秒钟的时间:

^{pr2}$

它看起来是这样的(我不得不重新缩放它,因为它太大了,不能这样做):

Mercator Map

可能外部for循环也会被矢量化,但我想这要困难得多。在

相关问题 更多 >