List of coordinates between irregular points in python

99封情书 提交于 2019-12-05 21:18:34

Use Bresenham's line algorithm. You can find a simple python implementation here. Here’s a modified version of that implementation, which, given a starting and ending point, can return a list of intermediate points:

def line(x0, y0, x1, y1):
        "Bresenham's line algorithm"
        points_in_line = []
        dx = abs(x1 - x0)
        dy = abs(y1 - y0)
        x, y = x0, y0
        sx = -1 if x0 > x1 else 1
        sy = -1 if y0 > y1 else 1
        if dx > dy:
            err = dx / 2.0
            while x != x1:
                points_in_line.append((x, y))
                err -= dy
                if err < 0:
                    y += sy
                    err += dx
                x += sx
        else:
            err = dy / 2.0
            while y != y1:
                points_in_line.append((x, y))
                err -= dx
                if err < 0:
                    x += sx
                    err += dy
                y += sy
        points_in_line.append((x, y))
        return points_in_line

Perhaps it's an overkill but I'd just find the line equation and use a generator expression. To find the equation you can use this example algorithm which will return something like

lambda x: 2*x +1

With that we can do:

f = find_line_equation(A, B) #A B are tuples
points = [(x, f(x)) for x in range(min(A[0], B[0]), max(A[0], B[0]))]

This is assuming you want only integer points. You can also use this loop:

points = []
x = min(A[0], B[0])
increment = 0.1
while x <= max(A[0], B[0]):
    points.append((x, f(x))
    x += increment
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!