Directly “plot” line segments to numpy array

China☆狼群 提交于 2019-12-04 17:35:02

Drawing a line segment in an array is a fundamental capability of any graphics library. The simplest method is probably Bresenham's algorithm. The algorithm is simple and fast--when implemented in a fast language, that is. I wouldn't recommend implementing it in pure python. A drawback of the simplest version of the algorithm is that it is not anti-aliased. The lines show "jaggies". Search for "line drawing algorithms" for more advanced methods with better anti-aliasing.

I have a Cython implementation of Bresenham's algorithm in my eyediagram package. The function bres_segment_count increments the values in the input array along the straight line from (x0, y0) to (x1, y1). A modification that simply sets the array values to 1 would be a trivial change to that code.

For example,

In [21]: dim = 250

In [22]: num_sticks = 300

Each row of sticks contains [x0, y0, x1, y1], the end points of a "stick":

In [23]: sticks = np.random.randint(0, dim, size=(num_sticks, 4)).astype(np.int32)

In [24]: img = np.zeros((dim, dim), dtype=np.int32)

bres_segments_count draws each stick using Bresenham's algorithm. Note that instead of simply setting a value in the line to, say, 1, the values in img along the line are incremented.

In [25]: from eyediagram._brescount import bres_segments_count

In [26]: bres_segments_count(sticks, img)

In [27]: plt.imshow(img, interpolation='nearest', cmap=cm.hot)
Out[27]: <matplotlib.image.AxesImage at 0x10f94b110>

Here's the plot that is generated:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!