首页 > 解决方案 > 计算椭圆之间相交的面积 - python

问题描述

我的目标是计算两个椭圆之间相交的面积。下面计算两个固定坐标之间的区域,但我希望使用一个椭圆的移动坐标来迭代这个过程,同时保持第二个椭圆固定。

使用下面,ellipse1将保持不变,并将使用来自和中ellipse2的坐标。XYdf

预期的输出将有望返回每个时间点的区域,四舍五入到小数点后 2 位,作为单独的列标记为'Area'

df = pd.DataFrame({        
    'Time' : [1,2,3,4,5],                               
    'X' : [3.0,4.5,5.0,10.0,3.0],
    'Y' : [1.0,0.0,-1.0,-2.0,-3.0],         
    })

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(figsize = (6,6))

ax.set_xlim([-20,20])
ax.set_ylim([-20,20])

ellipse1 = create_ellipse((0,0),(5,10),0)
verts1 = np.array(ellipse1.exterior.coords.xy)
patch1 = Polygon(verts1.T,color = 'red', alpha = 0.5)
ax.add_patch(patch1)

ellipse2 = create_ellipse((3.0,1.0),(5,5),0)
verts2 = np.array(ellipse2.exterior.coords.xy)
patch2 = Polygon(verts2.T,color = 'blue', alpha = 0.5)
ax.add_patch(patch2)

##compute intersect 
intersect = ellipse1.intersection(ellipse2)
verts3 = np.array(intersect.exterior.coords.xy)
patch3 = Polygon(verts3.T, facecolor = 'none', edgecolor = 'black')
ax.add_patch(patch3)

##compute intersected area
print(intersect.area)

预期输出:

   Time     X    Y   Area
0     1   3.0  1.0  56.51
1     2   4.5  0.0  46.99
2     3   5.0 -1.0  36.75
3     4  10.0 -2.0   0.00
4     5   3.0 -3.0  54.03

标签: pythonmatplotlibintersection

解决方案


如果我清楚地理解了你,你就快到了;您只需要在数据框中使用一种循环即可。即使由于 apply 可能效率不高,这也可以解决问题(更好的方法可能是跳到 geopandas,但我认为这里的这种方法对您来说更容易理解):

ellipse1 = create_ellipse((0,0),(5,10),0)

df['ellipse2']  = df[['X', 'Y']].apply(
        lambda xy:create_ellipse([*xy],(5,5),0),
        axis=1
        )
df['Area'] = df['ellipse2'].apply(lambda x: ellipse1.intersection(x).area)
df.drop('ellipse2', axis=1, inplace=True)
print(df)

退货

   Time     X    Y       Area
0     1   3.0  1.0  56.518719
1     2   4.5  0.0  41.997447
2     3   5.0 -1.0  36.746078
3     4  10.0 -2.0   0.000000
4     5   3.0 -3.0  54.029912

推荐阅读