在地图上划分长度为1的部分方式

时间:2011-02-12 10:50:03

标签: python arrays algorithm

我有这些坐标:

coord = [(10,10), (13,10), (13,13)]

现在我需要新的坐标。 两个坐标之间的路径总是一个。 例如:

(10,10)
(11,10)
(12,10)
(13,10)
(13,11)
(13,12)
(13,13)

有什么想法吗?

我找到了解决方案。

for n in range(len(coord)-1):
    lengthx = coord[n+1][0] - coord[n][0]
    lengthy = coord[n+1][1] - coord[n][1]
    length = (lengthx**2 + lengthy**2)**.5
    for m in range(length):
        print coord[n][0]+lengthx/length*m, coord[n][1]+lengthy/length*m

1 个答案:

答案 0 :(得分:1)

Bresenham's line algorithm上的一个简单变体将只使用整数运算实现你想要的东西(所以它应该明显更快):

def steps(path):
    if len(path) > 0:
        for i in range(1, len(path)):
            for step in steps_between(path[i - 1], path[i]):
                yield step
        yield path[-1]


def steps_between(start, end):
    x0, y0 = start
    x1, y1 = end

    steep = abs(y1 - y0) > abs(x1 - x0)
    if steep:
        x0, y0 = y0, x0
        x1, y1 = y1, x1

    if y0 > y1:
        x0, x1 = x1, x0
        y0, y1 = y1, y0

    if y0 < y1:
        ystep = 1
    else:
        ystep = -1

    deltax = x1 - x0
    deltay = abs(y1 - y0)
    error = -deltax / 2

    y = y0
    for x in range(x0, x1):
        if steep:
            yield (y, x)
        else:
            yield (x, y)

        error += deltay
        if error > 0:
            y += ystep
            error -= deltax
            if steep:
                yield (y, x)
            else:
                yield (x, y)

coords = [(10, 10), (13, 10), (13, 13)]
print "\n".join(str(step) for step in steps(coords))

以上版画:

(10, 10)
(11, 10)
(12, 10)
(13, 10)
(13, 11)
(13, 12)
(13, 13)

当然,当xy在路径上的两点之间发生变化时,Bresenham按预期工作:

coords = [(10, 10), (13, 12), (15, 13)]
print "\n".join(str(step) for step in steps(coords))

打印:

(10, 10)
(11, 10)
(11, 11)
(12, 11)
(12, 12)
(13, 12)
(14, 12)
(14, 13)
(15, 13)