Drawing polygons in numpy arrays

I am trying to draw polygons as follows:

In [1]: canvas = numpy.zeros((12, 12), dtype=int) In [2]: mahotas.polygon.fill_polygon( ...: [(1, 1), (1, 10), (10, 10), (10, 1)], ...: canvas) In [3]: canvas Out[3]: array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) 

I would expect the following output:

 array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) 

Why are [(10,2):(10:10)] still zeros? Is there any other way to draw a filled polygon into an array?

+4
source share
3 answers

This is a strange result. I found that if you change the order of the glasses, he draws the full number. 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 the test program:

 import numpy import mahotas.polygon def run(n, reverse=0): canvas = numpy.zeros((n, n), dtype=int) lim = n-2 print '\n%dx %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]] 
+1
source

If polygons are always rectangles, we need only 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
source

I think a reversal is required because numpy refers to massive coordinates as y, x (row, column), where most other programs return coordinates as x, y.

0
source

Source: https://habr.com/ru/post/1347176/


All Articles