ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python – 我对Bresenham算法的实现在特定角度的线路上失败了

2019-07-26 16:55:49  阅读:203  来源: 互联网

标签:python bresenham


我在Python中编写了Bresenham算法的实现(遵循Wikipedia article),除了某些角度的线条外,它的工作正常.应该在45度和90度之间或者在135度和270度之间延伸的所有线将沿着线y = x延伸.

这是我的代码:

def bresenham(origin, dest):
    # debug code
    print origin
    print dest
    # end debug code
    x0 = origin[0]; y0 = origin[1]
    x1 = dest[0]; y1 = dest[1]
    steep = abs(y1 - y0) > abs(x1 - x0)
    backward = x0 > x1

    if steep:
        x0, y0 = y0, x0
        x1, y1 = y1, x1
    if backward:
        x0, x1 = x1, x0
        y0, y1 = y1, y0

    dx = x1 - x0
    dy = abs(y1 - y0)
    error = dx / 2
    y = y0

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

    result = []
    #if x0 > x1: xstep = -1
    #else: xstep = 1
    # debug code
    print "x0 = %d" % (x0)
    print "x1 = %d" % (x1)
    print "y0 = %d" % (y0)
    print "y1 = %d" % (y1)
    for x in range(x0, x1):
        if steep: result.append((y,x))
        else: result.append((x,y))
        error -= dy
        if error < 0:
            y += ystep
            error += dx 
    # ensure the line extends from the starting point to the destination
    # and not vice-versa
    if backward: result.reverse()
    print result
    return result

有谁看到我搞砸了什么?

编辑:

我在函数中添加了一些打印代码.

(0,0)位于显示屏的左上角.

我的测试框架非常简单.这是一个独立的功能,所以我只给它两点:

origin = (416, 384)
dest = (440, 347)
bresenham(origin, dest)
(416, 384)
(440, 347)
x0 = 384
x1 = 347
y0 = 416
y1 = 440
[]

解决方法:

我不知道你为什么要使用xstep变量.你真的不需要使用你正在使用的算法.

@Gabe: xstep is needed because without it, if x0 > x1, then the for loop will terminate immediately, as the default step for a Python for loop is 1.

你不需要xstep变量的原因是因为,如果它向后移动,坐标已经被切换(在if后面:开头是条件的),所以终点现在是起点,反之亦然,这样我们现在仍然是从左到右.

你只需要这个:

result = []

for x in range(x0, x1):
    if steep: result.append((y, x))
    else: result.append((x, y))
    error -= dy
    if error < 0:
        y += ystep
        error += dx

return result

如果您想要从开始到结束点的顺序列表,那么您可以在结尾处进行检查:

if backward: return result.reverse()
else: return result

编辑:问题是在需要之前正在评估反向布尔值.如果陡峭的条件执行,那么值会改变,但到那时你的后向条件是不同的.要解决此问题,请将其设置为显式表达式,而不是使用向后布尔值:

if x0 > x1:
    # swapping here

然后,再次,因为您最后使用布尔值,您可以在条件之前定义它:

backward = x0 > x1

if backward:

标签:python,bresenham
来源: https://codeday.me/bug/20190726/1545351.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有