python-使用matplotlib的2个椭圆的重叠区域
作者:互联网
有谁知道是否可以使用matplotlib.patches.Ellipse计算两个椭圆的重叠面积.
我必须这样椭圆形:
我想计算重叠面积与各个椭圆的面积之比.
仅使用matplotlib.patches中的Ellipse是否可以
解决方法:
您无法使用matplotlib计算相交的面积(至少据我所知),但是您可以使用Shape进行计算,然后使用matplotlib可视化结果.这里是一个快速演示:
from matplotlib import pyplot as plt
from shapely.geometry.point import Point
from shapely import affinity
from matplotlib.patches import Polygon
import numpy as np
def create_ellipse(center, lengths, angle=0):
"""
create a shapely ellipse. adapted from
https://gis.stackexchange.com/a/243462
"""
circ = Point(center).buffer(1)
ell = affinity.scale(circ, int(lengths[0]), int(lengths[1]))
ellr = affinity.rotate(ell, angle)
return ellr
fig,ax = plt.subplots()
##these next few lines are pretty important because
##otherwise your ellipses might only be displayed partly
##or may be distorted
ax.set_xlim([-5,5])
ax.set_ylim([-5,5])
ax.set_aspect('equal')
##first ellipse in blue
ellipse1 = create_ellipse((0,0),(2,4),10)
verts1 = np.array(ellipse1.exterior.coords.xy)
patch1 = Polygon(verts1.T, color = 'blue', alpha = 0.5)
ax.add_patch(patch1)
##second ellipse in red
ellipse2 = create_ellipse((1,-1),(3,2),50)
verts2 = np.array(ellipse2.exterior.coords.xy)
patch2 = Polygon(verts2.T,color = 'red', alpha = 0.5)
ax.add_patch(patch2)
##the intersect will be outlined in black
intersect = ellipse1.intersection(ellipse2)
verts3 = np.array(intersect.exterior.coords.xy)
patch3 = Polygon(verts3.T, facecolor = 'none', edgecolor = 'black')
ax.add_patch(patch3)
##compute areas and ratios
print('area of ellipse 1:',ellipse1.area)
print('area of ellipse 2:',ellipse2.area)
print('area of intersect:',intersect.area)
print('intersect/ellipse1:', intersect.area/ellipse1.area)
print('intersect/ellipse2:', intersect.area/ellipse2.area)
plt.show()
结果图如下:
计算的区域(打印到终端)为:
area of ellipse 1: 25.09238792436751
area of ellipse 2: 18.81929094327563
area of intersect: 13.656608779925698
intersect/ellipse1: 0.5442530547945023
intersect/ellipse2: 0.7256707397260032
请注意,我修改了代码以从this post生成椭圆形多边形.希望这会有所帮助.
标签:python,matplotlib,geometry,ellipse 来源: https://codeday.me/bug/20191010/1885212.html