如何用 Python 绘制多边形?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43971259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:35:35  来源:igfitidea点击:

How to draw polygons with Python?

pythonplotpolygon

提问by W.Fan

I have input values of x, y coordinates in the following format:

我有以下格式的 x, y 坐标输入值:

[[1,1], [2,1], [2,2], [1,2], [0.5,1.5]]

I want to draw polygons, but I don't know how to draw them!

我想画多边形,但我不知道如何画它们!

Thanks

谢谢

回答by Julien

Using matplotlib.pyplot

使用 matplotlib.pyplot

import matplotlib.pyplot as plt

coord = [[1,1], [2,1], [2,2], [1,2], [0.5,1.5]]
coord.append(coord[0]) #repeat the first point to create a 'closed loop'

xs, ys = zip(*coord) #create lists of x and y values

plt.figure()
plt.plot(xs,ys) 
plt.show() # if you need...

回答by Nurjan

Another way to draw a polygon is this:

绘制多边形的另一种方法是:

import PIL.ImageDraw as ImageDraw
import PIL.Image as Image

image = Image.new("RGB", (640, 480))

draw = ImageDraw.Draw(image)

# points = ((1,1), (2,1), (2,2), (1,2), (0.5,1.5))
points = ((100, 100), (200, 100), (200, 200), (100, 200), (50, 150))
draw.polygon((points), fill=200)

image.show()

Note that you need to install the pillow library. Also, I scaled up your coordinates by the factor of 100 so that we can see the polygon on the 640 x 480 screen.

注意需要安装枕头库。此外,我将您的坐标放大了 100 倍,以便我们可以在 640 x 480 屏幕上看到多边形。

Hope this helps.

希望这可以帮助。

回答by Богдан Опир

Also, if you're drawing on window, use this:

另外,如果您在窗口上绘图,请使用以下命令:

dots = [[1,1], [2,1], [2,2], [1,2], [0.5,1.5]]
from tkinter import Canvas
c = Canvas(width=750, height=750)
c.pack()
out = []
for x,y in dots:
    out += [x*250, y*250]
c.create_polygon(*out, fill='#aaffff')#fill with any color html or name you want, like fill='blue'
c.update()

or also you may use this:

或者你也可以使用这个:

dots = [[1,1], [2,1], [2,2], [1,2], [0.5,1.5]]
out = []
for x,y in dots:
    out.append([x*250, y*250])
import pygame, sys
from pygame.locals import *
pygame.init()
DISPLAYSURF = pygame.display.set_mode((750, 750), 0, 32)
pygame.display.set_caption('WindowName')
DISPLAYSURF.fill((255,255,255))#< ; \/ - colours
pygame.draw.polygon(DISPLAYSURF, (0, 255,0), out)
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    pygame.display.update()

First needs tkinter, second - pygame. First loads faster, second draws faster, if you put DISPLAYSURF.filland than pygame.draw.polygonwith a bit different coordinates into loop, it will work better than the same thing in tkinter. So if your polygon is flying and bouncing around, use second, but if it's just stable thing, use first. Also, in python2 use from Tkinter, not from tkinter. I've checked this code on raspberrypi3, it works.

第一个需要tkinter,第二个pygame。第一个加载速度更快,第二个绘制速度更快,如果您将DISPLAYSURF.fillpygame.draw.polygon与稍微不同的坐标放入循环中,它将比 tkinter 中的相同内容更好。因此,如果您的多边形在飞行和弹跳,请使用第二个,但如果它只是稳定的东西,请先使用。另外,在 python2 中使用from Tkinter,而不是from tkinter. 我已经在 raspberrypi3 上检查过这段代码,它有效。

------------EDIT------------

- - - - - - 编辑 - - - - - -

A little bit more about PIL and PYPLOT methods, see another answers:

关于 PIL 和 PYPLOT 方法的更多信息,请参阅另一个答案:

matplotlibuses tkinter, maybe matplotlibis easier-to-use, but it's basically cooler tkinterwindow.

matplotlib使用tkinter,也许matplotlib更容易使用,但它基本上是凉爽的tkinter窗口。

PILin this case uses imagemagick, which is really good image editing tool

PIL在这种情况下使用imagemagick,这是一个非常好的图像编辑工具

If you also need to apply effects on image, use PIL.

如果您还需要对图像应用效果,请使用PIL.

If you need more difficult math-figures, use matplotlib.pyplot.

如果您需要更难的数学数字,请使用matplotlib.pyplot.

For animation, use pygame.

对于动画,请使用pygame.

For everything you don't know any better way to do something, use tkinter.

对于您不知道做某事的更好方法的所有内容,请使用tkinter.

tkinterinit is fast. pygameupdates are fast. pyplotis just a geometry tool.

tkinterinit 很快。pygame更新很快。pyplot只是一个几何工具。

回答by idiot

All the other answers seems veryhigh level, I guess that is my impression as a mechanical engineer. Here's a simple version of the code:

其他所有的答案看起来都非常高级,我想这是我作为机械工程师的印象。这是代码的简单版本:

from numpy import *
from matplotlib.pyplot import *
x = ([1,2,2,1,0.5,1]) 
y = ([1,1,2,2,1.5,1])
plot(x,y)
show()

回答by Alexandre Huat

If you want to draw polygons on a matrix representing an image, scikit-imagehas 3 functions for you:

如果您想在表示图像的矩阵上绘制多边形,scikit-image为您提供 3 个函数:

Correct me if your benchmark said the contrary, but I think these functions are quite fast.

如果您的基准测试相反,请纠正我,但我认为这些功能非常

Example

例子

import numpy as np
from skimage.draw import polygon2mask, polygon, polygon_perimeter

shape = (10, 10)  # image shape
points = [(5, -1), (-1, 5), (5, 11), (10, 5)]  # polygon points

imgp2 = polygon2mask(shape, points).astype(str)  # astype() converts bools to strings
imgp2[imgp2 == "True"] = "O"
imgp2[imgp2 == "False"] = "."

imgp = np.full(shape, ".")  # fill a n*d matrix with '.'
imgpp = imgp.copy()
points = np.transpose(points)  # change format to ([5, -1, 5, 10], [-1, 5, 11, 5])

rr, cc = polygon(*points, shape=shape)
imgp[rr, cc] = "O"

rr, cc = polygon_perimeter(*points, shape=shape, clip=True)
imgpp[rr, cc] = "O"

print(imgp2, imgp, imgpp, sep="\n\n")

Result:

结果:

[['.' '.' '.' '.' 'O' 'O' '.' '.' '.' '.']
 ['.' '.' '.' 'O' 'O' 'O' 'O' '.' '.' '.']
 ['.' '.' 'O' 'O' 'O' 'O' 'O' 'O' '.' '.']
 ['.' 'O' 'O' 'O' 'O' 'O' 'O' 'O' 'O' '.']
 ['O' 'O' 'O' 'O' 'O' 'O' 'O' 'O' 'O' 'O']
 ['O' 'O' 'O' 'O' 'O' 'O' 'O' 'O' 'O' 'O']
 ['.' 'O' 'O' 'O' 'O' 'O' 'O' 'O' 'O' 'O']
 ['.' '.' 'O' 'O' 'O' 'O' 'O' 'O' 'O' '.']
 ['.' '.' '.' 'O' 'O' 'O' 'O' 'O' '.' '.']
 ['.' '.' '.' '.' 'O' 'O' 'O' '.' '.' '.']]

[['.' '.' '.' '.' 'O' 'O' '.' '.' '.' '.']
 ['.' '.' '.' 'O' 'O' 'O' 'O' '.' '.' '.']
 ['.' '.' 'O' 'O' 'O' 'O' 'O' 'O' '.' '.']
 ['.' 'O' 'O' 'O' 'O' 'O' 'O' 'O' 'O' '.']
 ['O' 'O' 'O' 'O' 'O' 'O' 'O' 'O' 'O' 'O']
 ['O' 'O' 'O' 'O' 'O' 'O' 'O' 'O' 'O' 'O']
 ['.' 'O' 'O' 'O' 'O' 'O' 'O' 'O' 'O' 'O']
 ['.' '.' 'O' 'O' 'O' 'O' 'O' 'O' 'O' '.']
 ['.' '.' '.' 'O' 'O' 'O' 'O' 'O' '.' '.']
 ['.' '.' '.' '.' 'O' 'O' 'O' '.' '.' '.']]

[['.' '.' '.' '.' 'O' 'O' 'O' '.' '.' '.']
 ['.' '.' '.' 'O' '.' '.' '.' 'O' '.' '.']
 ['.' '.' 'O' '.' '.' '.' '.' '.' 'O' '.']
 ['.' 'O' '.' '.' '.' '.' '.' '.' '.' 'O']
 ['O' '.' '.' '.' '.' '.' '.' '.' '.' 'O']
 ['O' '.' '.' '.' '.' '.' '.' '.' '.' 'O']
 ['O' '.' '.' '.' '.' '.' '.' '.' '.' 'O']
 ['.' 'O' 'O' '.' '.' '.' '.' '.' '.' 'O']
 ['.' '.' '.' 'O' '.' '.' '.' 'O' 'O' '.']
 ['.' '.' '.' '.' 'O' 'O' 'O' '.' '.' '.']]