找到两个椭圆的交点

10 投票
3 回答
11698 浏览
提问于 2025-04-17 19:17

我正在用Python写一个基本的二维图形库,主要是为了处理SVG图形,现在我不知道怎么高效地计算两个椭圆的交点。

每个椭圆是由以下变量定义的(都是浮点数):

c: center point (x, y)
hradius: "horizontal" radius
vradius: "vertical" radius
phi: rotation from coordinate system's x-axis to ellipse's horizontal axis

除了椭圆完全重合的情况外,两个椭圆可能有0到4个交点(没有交点、相切、部分重叠、部分重叠且内部相切,以及完全重叠)。

我找到了一些可能的解决方案:

  • SymPy几何模块 - 这个方法基本上是把椭圆的方程放进SymPy的求解器里。我不太确定在没有求解器的情况下这样做是否合理。(顺便说一下,我本来想用SymPy,但它在处理复杂浮点数时表现得很糟糕)
  • 如何检测椭圆是否与圆相交 - 这个方法可能可以改编成用于两个椭圆,但我对如何把它变成合理的代码有点模糊。
  • 椭圆与椭圆的交点计算 - 答案中提到的库(CADEMIA)可能有一个不错的算法,但我甚至不知道它是否是开源的。
  • 维基百科:两个圆锥曲线的交点 - 我对线性代数的理解不够,无法理解这个解决方案。

有没有什么建议可以帮助我计算交点?速度(可能需要计算很多交点)和优雅性是主要考虑因素。如果能提供代码那就太好了,但即使是一个好的方向也会很有帮助。

3 个回答

3

你可以使用这里展示的方法:https://math.stackexchange.com/questions/864070/how-to-determine-if-two-ellipse-have-at-least-one-intersection-point/864186#864186

首先,你需要能够在一个方向上重新调整椭圆的大小。为此,你需要计算椭圆作为圆锥曲线的系数,调整大小,然后找回椭圆的新几何参数:中心、轴和角度。

接下来,你的问题就变成了找出椭圆到原点的距离。要解决这个问题,你需要进行一些迭代。这里有一个可能的完整实现……

from math import *

def bisect(f,t_0,t_1,err=0.0001,max_iter=100):
    iter = 0
    ft_0 = f(t_0)
    ft_1 = f(t_1)
    assert ft_0*ft_1 <= 0.0
    while True:
        t = 0.5*(t_0+t_1)
        ft = f(t)
        if iter>=max_iter or ft<err:
            return t
        if ft * ft_0 <= 0.0:
            t_1 = t
            ft_1 = ft
        else:
            t_0 = t
            ft_0 = ft
        iter += 1

class Ellipse(object):
    def __init__(self,center,radius,angle=0.0):
        assert len(center) == 2
        assert len(radius) == 2
        self.center = center
        self.radius = radius
        self.angle = angle

    def distance_from_origin(self):
        """                                                                           
        Ellipse equation:                                                             
        (x-center_x)^2/radius_x^2 + (y-center_y)^2/radius_y^2 = 1                     
        x = center_x + radius_x * cos(t)                                              
        y = center_y + radius_y * sin(t)                                              
        """
        center = self.center
        radius = self.radius

        # rotate ellipse of -angle to become axis aligned                             

        c,s = cos(self.angle),sin(self.angle)
        center = (c * center[0] + s * center[1],
                  -s* center[0] + c * center[1])

        f = lambda t: (radius[1]*(center[1] + radius[1]*sin(t))*cos(t) -
                       radius[0]*(center[0] + radius[0]*cos(t))*sin(t))

        if center[0] > 0.0:
            if center[1] > 0.0:
                t_0, t_1 = -pi, -pi/2
            else:
                t_0, t_1 = pi/2, pi
        else:
            if center[1] > 0.0:
                t_0, t_1 = -pi/2, 0
            else:
                t_0, t_1 = 0, pi/2

        t = bisect(f,t_0,t_1)
        x = center[0] + radius[0]*cos(t)
        y = center[1] + radius[1]*sin(t)
        return sqrt(x**2 + y**2)

print Ellipse((1.0,-1.0),(2.0,0.5)).distance_from_origin()
4

看了一下sympy,我觉得它有你需要的所有功能。
(我试着给你提供一些示例代码,但很遗憾,我在用gmpy2安装sympy时失败了,结果只能用无用的Python内置数学库)

你可以使用:

  • 一个椭圆,它有一个旋转的方法,可以和其他椭圆相交
  • 或者一个任意相交的函数,可以接受多个被称为“几何实体”的东西。

从他们的示例来看,我觉得两个椭圆相交是完全可能的:

>>> from sympy import Ellipse, Point, Line, sqrt
>>> e = Ellipse(Point(0, 0), 5, 7)
...
>>> e.intersection(Ellipse(Point(1, 0), 4, 3))
[Point(0, -3*sqrt(15)/4), Point(0, 3*sqrt(15)/4)]
>>> e.intersection(Ellipse(Point(5, 0), 4, 3))
[Point(2, -3*sqrt(7)/4), Point(2, 3*sqrt(7)/4)]
>>> e.intersection(Ellipse(Point(100500, 0), 4, 3))
[]
>>> e.intersection(Ellipse(Point(0, 0), 3, 4))
[Point(-363/175, -48*sqrt(111)/175), Point(-363/175, 48*sqrt(111)/175),
Point(3, 0)]
>>> e.intersection(Ellipse(Point(-1, 0), 3, 4))
[Point(-17/5, -12/5), Point(-17/5, 12/5), Point(7/5, -12/5),
Point(7/5, 12/5)] 

编辑:因为sympy不支持一般的椭圆方程(ax^2 + bx + cy^2 + dy + exy + f),

所以你需要自己构建方程并进行变换,然后使用他们的求解器来找到交点。

14

在数学中,你需要把椭圆表示成二次方程,然后去解这个方程。我找到了一份文档,里面有所有的计算过程,不过在Python中实现起来可能需要一些时间。

另外一种方法是把椭圆近似成多边形的线段,然后用shapely这个库来找交点,这里有一段代码:

import numpy as np
from shapely.geometry.polygon import LinearRing

def ellipse_polyline(ellipses, n=100):
    t = linspace(0, 2*np.pi, n, endpoint=False)
    st = np.sin(t)
    ct = np.cos(t)
    result = []
    for x0, y0, a, b, angle in ellipses:
        angle = np.deg2rad(angle)
        sa = np.sin(angle)
        ca = np.cos(angle)
        p = np.empty((n, 2))
        p[:, 0] = x0 + a * ca * ct - b * sa * st
        p[:, 1] = y0 + a * sa * ct + b * ca * st
        result.append(p)
    return result

def intersections(a, b):
    ea = LinearRing(a)
    eb = LinearRing(b)
    mp = ea.intersection(eb)

    x = [p.x for p in mp]
    y = [p.y for p in mp]
    return x, y

ellipses = [(1, 1, 2, 1, 45), (2, 0.5, 5, 1.5, -30)]
a, b = ellipse_polyline(ellipses)
x, y = intersections(a, b)
plot(x, y, "o")
plot(a[:,0], a[:,1])
plot(b[:,0], b[:,1])

输出结果是:

enter image description here

在我的电脑上大约需要1.5毫秒。

撰写回答