基于Python實現(xiàn)繪制一個足球
前情提要
如果想優(yōu)雅地繪制一個足球,那首先需要繪制正二十面體:用Python繪制正二十面體
其核心代碼為
import numpy as np
from itertools import product
G = (np.sqrt(5)-1)/2
def getVertex():
pt2 = [(a,b) for a,b in product([1,-1], [G, -G])]
pts = [(a,b,0) for a,b in pt2]
pts += [(0,a,b) for a,b in pt2]
pts += [(b,0,a) for a,b in pt2]
return np.array(pts)
def getDisMat(pts):
N = len(pts)
dMat = np.ones([N,N])*np.inf
for i in range(N):
for j in range(i):
dMat[i,j] = np.linalg.norm([pts[i]-pts[j]])
return dMat
pts = getVertex()
dMat = getDisMat(pts)
# 由于存在舍入誤差,所以得到的邊的數(shù)值可能不唯一
ix, jx = np.where((dMat-np.min(dMat))<0.01)
# 獲取正二十面體的邊
edges = [pts[[i,j]] for i,j in zip(ix, jx)]
def isFace(e1, e2, e3):
pts = np.vstack([e1, e2, e3])
pts = np.unique(pts, axis=0)
return len(pts)==3
from itertools import combinations
# 獲取正二十面體的面
faces = [es for es in combinations(edges, 3)
if isFace(*es)]
為了克服plot_trisurf在xy坐標系中的bug,需要對足球做一點旋轉(zhuǎn),所以下面要寫入旋轉(zhuǎn)矩陣。
# 將角度轉(zhuǎn)弧度后再求余弦
cos = lambda th : np.cos(np.deg2rad(th))
sin = lambda th : np.sin(np.deg2rad(th))
# 即 Rx(th) => Matrix
Rx = lambda th : np.array([
[1, 0, 0],
[0, cos(th), -sin(th)],
[0, sin(th), cos(th)]])
Ry = lambda th : np.array([
[cos(th), 0, sin(th)],
[0 , 1, 0],
[-sin(th), 0, cos(th)]
])
Rz = lambda th : np.array([
[cos(th) , sin(th), 0],
[-sin(th), cos(th), 0],
[0 , 0, 1]])
最后得到的正二十面體為

先畫六邊形
足球其實就是正二十面體削掉頂點,正二十面體有20個面和12個頂點,每個面都是三角形。削掉頂點對于三角形而言就是削掉三個角,如果恰好選擇在1/3的位置削角,則三角形就變成正六邊形;而每個頂點處剛好有5條棱,頂點削去之后就變成了正五邊形。
而正好足球的六邊形和五邊形有著不同的顏色,所以可以分步繪制,先來搞定六邊形。
由于此前已經(jīng)得到了正二十面體的所有面,同時還有這個面對應的所有邊,故而只需在每一條邊的1/3 和2/3處截斷,就可以得到足球的正六邊形。
def getHexEdges(face):
pts = []
for st,ed in face:
pts.append((2*st+ed)/3)
pts.append((st+2*ed)/3)
return np.vstack(pts)
ax = plt.subplot(projection='3d')
for f in faces:
pt = getHexEdges(f)
pt = Rx(1)@Ry(1)@pt.T
ax.plot_trisurf(*pt, color="white")
于是,一個有窟窿的足球就很輕松地被畫出來了

再畫五邊形
接下來要做的是,將五邊形的窟窿補上,正如一開始說的,這個五邊形可以理解為削去頂點而得到的,所以第一件事,就是要找到一個頂點周圍的所有邊。具體方法就是,對每一個頂點遍歷所有邊,如果某條邊中存在這個頂點,那么就把這個邊納入到這個頂點的連接邊。
def getPtEdges(pts, edges):
N = len(pts)
pEdge = [[] for pt in pts]
for i,e in product(range(N),edges):
if (pts[i] == e[0]).all():
pt = (2*pts[i]+e[1])/3
elif (pts[i] == e[1]).all():
pt = (2*pts[i]+e[0])/3
else:
continue
pEdge[i].append(pt)
return np.array(pEdge)
pEdge = getPtEdges(pts, edges)
接下來,就可以繪制足球了
ax = plt.subplot(projection='3d')
for f in faces:
pt = getHexEdges(f)
pt = Rx(1)@Ry(1)@pt.T
ax.plot_trisurf(*pt, color="white")
for pt in pEdge:
pt = Rx(1)@Ry(1)@pt.T
ax.plot_trisurf(*pt, color="black")
plt.show()
效果為

以上就是基于Python實現(xiàn)繪制一個足球的詳細內(nèi)容,更多關于Python足球的資料請關注腳本之家其它相關文章!
相關文章
python實現(xiàn)動態(tài)GIF英數(shù)驗證碼識別示例
這篇文章主要為大家介紹了python實現(xiàn)動態(tài)GIF英數(shù)驗證碼識別示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2024-01-01
Python對Excel按列值篩選并拆分表格到多個文件的代碼
這篇文章主要介紹了Python對Excel按列值篩選并拆分表格到多個文件,本文通過代碼給大家介紹的非常詳細,需要的朋友可以參考下2019-11-11

