Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

python - Drawing polygons in numpy arrays

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), (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'd expect the following output though:

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 another way to draw a filled polygon to an array?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 '
%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]]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...