Drawing polygons in numpy arrays

前端 未结 3 1161
灰色年华
灰色年华 2020-12-19 12:22

I\'m trying to draw polygons like this:

In [1]: canvas = numpy.zeros((12, 12), dtype=int)

In [2]: mahotas.polygon.fill_polygon(
   ...: [(1, 1), (1, 10), (1         


        
相关标签:
3条回答
  • 2020-12-19 12:39

    If the polygons are always rectangles, then we only need two points and:

    import numpy
    canvas = numpy.zeros((12, 12), dtype=int)
    points = [(1, 1), (1, 10), (10, 10), (10, 1)]
    start_pt, end_pt = min(points), max(points)
    canvas[start_pt[1]:end_pt[1]+1, start_pt[0]:end_pt[0]+1] = 1
    
    0 讨论(0)
  • 2020-12-19 12:42

    It is a strange result. I found that if you reverse the order of the points it draws the complete figure. In other words:

    # this is broken
    pts = [(1, 1), (1, 10), (10, 10), (10, 1)]
    # this works
    pts = [(1, 1), (10, 1), (10, 10), (1, 10)]
    

    Here is a test program:

    import numpy
    import mahotas.polygon
    
    def run(n, reverse=0):
        canvas = numpy.zeros((n, n), dtype=int)
        lim = n-2
        print '\n%d x %d, lim=%d reverse=%d' % (n, n, lim, reverse)
        pts = [(1, 1), (1, lim), (lim, lim), (lim, 1), (1, 1)]
        if reverse:
            pts.reverse()
        mahotas.polygon.fill_polygon(pts, canvas)
        return canvas
    
    for rev in (0, 1):
        for n in range(3, 14):
            print run(n, rev)
    

    Examples:

    6 x 6, lim=4 reverse=0
    [[0 0 0 0 0 0]
     [0 1 0 0 1 0]
     [0 1 1 1 1 0]
     [0 1 1 1 1 0]
     [0 1 0 0 0 0]
     [0 0 0 0 0 0]]
    
    6 x 6, lim=4 reverse=1
    [[0 0 0 0 0 0]
     [0 1 1 1 1 0]
     [0 1 1 1 1 0]
     [0 1 1 1 1 0]
     [0 1 1 1 1 0]
     [0 0 0 0 0 0]]
    
    0 讨论(0)
  • 2020-12-19 13:01

    I think the reversal is required because numpy references array coordinates as y,x (row, column) where most other programs issue coordinates as x,y.

    0 讨论(0)
提交回复
热议问题