簡體   English   中英

如何用 Python 繪制多邊形?

[英]How to draw polygons with Python?

我有以下格式的 x、y 坐標的輸入值:

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

我想畫多邊形,但不知道怎么畫!

謝謝

使用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...

繪制多邊形的另一種方法是:

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()

注意需要安裝枕頭庫。 此外,我將您的坐標放大了 100 倍,以便我們可以在 640 x 480 屏幕上看到多邊形。

希望這可以幫助。

另外,如果您在窗口上繪圖,請使用以下命令:

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()

或者你也可以使用這個:

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()

首先需要tkinter ,其次需要pygame 第一次加載更快,第二次繪制更快,如果你把DISPLAYSURF.fillpygame.draw.polygon放在循環中,它的坐標有點不同,它會比 tkinter 中的相同東西更好。 因此,如果您的多邊形在飛行和彈跳,請使用第二個,但如果它只是穩定的東西,請先使用。 此外,在 python2 中使用from Tkinter ,而不是from tkinter 我已經在 raspberrypi3 上檢查過這段代碼,它有效。

- - - - - - 編輯 - - - - - -

關於 PIL 和 PYPLOT 方法的更多信息,請參閱另一個答案:

matplotlib使用tkinter ,也許matplotlib更易於使用,但它基本上是更酷的tkinter窗口。

在這種情況下, PIL使用imagemagick ,這是一個非常好的圖像編輯工具

如果您還需要對圖像應用效果,請使用PIL

如果您需要更難的數學數字,請使用matplotlib.pyplot

對於動畫,請使用pygame

對於您不知道做某事的更好方法的所有內容,請使用tkinter

tkinter init 很快。 pygame更新很快。 pyplot只是一個幾何工具。

其他所有的答案看起來都非常高級,我想這是我作為機械工程師的印象。 這是代碼的簡單版本:

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()
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon

y = np.array([[1,1], [2,1], [2,2], [1,2], [0.5,1.5]])

p = Polygon(y, facecolor = 'k')

fig,ax = plt.subplots()

ax.add_patch(p)
ax.set_xlim([0,3])
ax.set_ylim([0,3])
plt.show()

如果您想在表示圖像的矩陣上繪制多邊形, scikit-image為您提供 3 個函數:

如果您的基准測試相反,請糾正我,但我認為這些功能非常

例子

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")

結果:

[['.' '.' '.' '.' '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' '.' '.' '.']]

matplotlib.patches有一個名為Polygon的函數,它可以像from matplotlib.patches import Polygon那樣from matplotlib.patches import Polygon 您可以使用軸對象的add_patch方法來繪制多邊形。

from matplotlib.patches import Polygon
import matplotlib.pyplot as plt

polygon1 = Polygon([(0,5), (1,1), (3,0),])

fig, ax = plt.subplots(1,1)

ax.add_patch(polygon1)

plt.ylim(0,6)
plt.xlim(0,6)

在此處輸入圖片說明

這是一個兩行解決方案(假設您導入了matplotlib.pyplot並定義了多邊形 - 如果沒有,則為四行^^):

import matplotlib.pyplot as plt
poly = [[1,1], [2,1], [2,2], [1,2], [0.5,1.5]]

plt.plot(*np.column_stack(poly+[poly[0]]))
plt.show()

tkinter畫布非常強大,可以輕松繪制具有許多可操作的內置屬性的各種多邊形:

示例(截圖):

在此處輸入圖片說明

示例代碼:

import tkinter as tk


def _scale_and_flip(point, offset):
    """
    scales the provided point and flips the y axis so it points upwards
    origin (0, 0) at the bottom left corner of the screen
    returns the point scaled and flipped
    """
    x, y = point
    ox, oy = offset
    return ((x+ox) * SCALE, HEIGHT - (y+oy) * SCALE)

def scale_and_flip(polygon, offset=(0, 0)):
    """
    scales the provided point and flips the y axis so it points upwards
    origin (0, 0) at the bottom left corner of the screen
    returns a sequence of scaled and flipped points representing the polygon ready to render
    """
    return [_scale_and_flip(point, offset) for point in polygon]


if __name__ == '__main__':
    WIDTH, HEIGHT = 500, 500
    SCALE = 100
    polygon_points = [[1, 1], [2, 1], [2, 2], [1, 2], [0.5, 1.5]]

    root = tk.Tk()
    canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT, bg='cyan')
    canvas.pack()

    canvas.create_polygon(scale_and_flip(polygon_points), fill='beige', outline='black')
    canvas.create_polygon(scale_and_flip(polygon_points, (0, 2)), fill='beige', outline='black', smooth=True)
    canvas.create_polygon(scale_and_flip(polygon_points, (2, 0)), fill='beige', outline='black', dash=(1, 3))
    canvas.create_polygon(scale_and_flip(polygon_points, (2, 2)), fill='beige', outline='black', dash=(1, 3), smooth=True)

    root.mainloop()

更多tk.Canvas.create_polygon選項和屬性可以在這里找到

盡管有很多答案,但這里是我使用 Turtle 模塊的方法。 turtle 模塊以面向對象和面向過程的方式提供海龜圖形原語。

import turtle
  

t = turtle.Turtle()
  
# input for number of sides 
n_sides = int(input("Enter the sides of the polygon : "))
  
# length of the polygon
l_sides = int(input("Enter the length of the polygon : "))
  
  
for _ in range(n_sides):
    turtle.fd(l_sides)
    turtle.rt(360 / n_sides)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM