Closest point on a circle to a line segment python

2019-02-28 08:33发布

I need to find the closest distance between a box and a circle, however, I realize this can be broken up into the closest distance between a line segment and a circle.

Given

  • I have a line segment of two points point1_x,point1_y and point2_x, point2_y
  • I have a circle with center circle_x, circle_y and radius radius

Question

Is there a python library that will support this out of the box and if not can somebody present a function to do so?

(I belive I have to locate the tangent point on the circle with the same slope as the line?)

2条回答
smile是对你的礼貌
2楼-- · 2019-02-28 09:04

There exists a method to find the closest distance from circle to rectangle (axis-oriented here).
Rectangle sides divide plane into 9 pieces. We can find what piece (central, left-top, left etc) contains circle center, and calculate needed distance. Rectangle ABCD and circle center E:

enter image description here

Delphi code:

//returns closest distance from circle to rectangle
//0 if intersection or inclusion occurs
function CircleRectDistance(CX, CY, CR: Integer; RR: TRect): Double;
var
  wh, hh, dx, dy, t, SquaredDist: Double;
begin
  SquaredDist := 0;

  //halfwidth and halfheight
  wh := 0.5 * (RR.Right - RR.Left);
  hh := 0.5 * (RR.Bottom - RR.Top);

  //distances to rectangle center
  dx := CX - 0.5 * (RR.Left + RR.Right);
  dy := CY - 0.5 * (RR.Top + RR.Bottom);

  //rectangle sides divide plane to 9 parts,
  t := dx + wh;
  if t < 0 then
    SquaredDist := t * t
  else begin
    t := dx - wh;
    if t > 0 then
      SquaredDist := t * t
  end;
  t := dy + hh;
  if t < 0 then
    SquaredDist := SquaredDist + t * t
  else begin
    t := dy - hh;
    if t > 0 then
      SquaredDist := SquaredDist + t * t
  end;

  if SquaredDist < CR * CR  then
    Result := 0
  else
    Result := Sqrt(SquaredDist)- CR;
end;
查看更多
小情绪 Triste *
3楼-- · 2019-02-28 09:25

The euclid module. Install with:

pip install euclid

Then use it like this:

>>> from euclid import *

>>> circ = Circle(Point2(3., 2.), 2.)
>>> line = Line2(Point2(0., 0.), Point2(-1., 1.))
>>> line.distance(circ)
1.5355339059327378
查看更多
登录 后发表回答