有没有办法在python或opencv中绘制折线或轮廓线以填充三角形?

时间:2019-05-27 09:04:21

标签: python opencv matplotlib

post提供了一种绝佳的方法来绘制直线以填充三角形(称为此Figure_1),例如

enter image description here

最初的帖子是Wolfram语言的,我正在尝试在Python中绘制类似的图。

代码如下:

import numpy as np
xlist = np.linspace(-3.0, 3.0, 3)
ylist = np.linspace(-3.0, 3.0, 3)
X, Y = np.meshgrid(xlist, ylist)
Z = np.sqrt(X**2 + Y**2)

import matplotlib.pyplot as plt
f, ax = plt.subplots(figsize=(6,6))
cp = ax.contour(X, Y, Z, levels = [0.25,1,2,3], colors=('k','r',))
ax.clabel(cp, inline=True, fontsize=10)
plt.title('Contour Plot')
plt.grid(True)
plt.show()

输出图:

enter image description here

是菱形而不是想要的三角形,有没有办法绘制如图_1所示的折线或轮廓线?

1 个答案:

答案 0 :(得分:1)

plt.tricontour可以满足您的需求。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.tri as tri




# first load some data:  format x1,x2,x3,value
test_data = np.array([[0,0,1,0],
                      [0,1,0,0],
                      [1,0,0,0],
                      [0.25,0.25,0.5,1],
                      [0.25,0.5,0.25,1],
                      [0.5,0.25,0.25,1]])

# barycentric coords: (a,b,c)
a=test_data[:,0]
b=test_data[:,1]
c=test_data[:,2]

# values is stored in the last column
v = test_data[:,-1]

# translate the data to cartesian corrds
x = 0.5 * ( 2.*b+c ) / ( a+b+c )
y = 0.5*np.sqrt(3) * c / (a+b+c)


# create a triangulation out of these points
T = tri.Triangulation(x,y)

# plot the contour
plt.tricontour(x,y,T.triangles,v)
plt.show()

情节

enter image description here

相关问题