How to find given 2D point position based on axis system - computational-geometry

I have a axis system(origin,u direction,v direction).How to know given 2D point lie on the line which is used to denote the u or v direction line(ie, u=0 or v =0)?

The axis OU has equation
Uy.(X - Ox) - Ux.(Y - Oy) = 0
and similarly for OV
Vy.(X - Ox) - Vx.(Y - Oy) = 0
Because of rounding errors, strict equality to zero will not hold, but if the vectors U and V are normalized,
|Uy.(X - Ox) - Ux.(Y - Oy)|
and
|Vy.(X - Ox) - Vx.(Y - Oy)|
are the shortest distances from the point (X, Y) to the axes.

If "given 2D point" P coordinates are presented in fixed coordinate system, then you have to represent vector P-origin in o-u-v basis.
op = P - origin
s * u.x + t * v.x = op.x
s * u.y + t * v.y = op.y
Solve last system of linear equations for unknown coefficients s and t. Check for zero coefficients.

Related

determining algorithm for calculating a point intersecting a circle where the segment crosses from inside to the outside of the circle

I have a line segment between points A and B. A is inside a circle with a center at 0,0 with a radius of R. I am stumped trying to come up with an efficient way to calculate the intersection of line segment AB with this circle.
This is a mere second degree equation resolution
Line is y=A.x +B , where A and B are constants
Circle is y^2=R^2 - x^2 , where R is the radius, and circle center is 0,0
so (A.x+B)^2=R^2-x^2 => A^2.x^2 +2.A.x.B +B^2 =R^2 -x^2 =>
(A^2+1).x^2 + 2.A.B.x +B^2-R^2 =0
The algorithm is :
let P=A^2+1 , G=2.A.B , H=B^2-R^2
The equation is : P.x^2 + G.x + H=0
that gives 3 cases depending on delta
delta=G^2-4*P*H
If delta<0 => no intersections
if delta=0 => intersect in 1 point : x=-G/2*P and y=Ax+B
if delta>0 => intersect in 2 points : x1=(-G-sqrt(delta))/(2*P) , y1=Ax1+B and x2=(-G+sqrt(delta))/(2*P) ,y2=Ax2+B (where sqrt is the square root)
Then you just have to determine which of the two resultant answers give a point that is between A and B.
Let's call two resultants I1 and I2. To determine which one is the answer, you need to check directions of A->I1 and A->I2 vectors against A->B, where A is the point that is located inside the circle:
% line: y = mx + b
m = (yB - yA) / (xB - xA);
b = yA - m * xA;
% circle: x^2 + y^2 = r^2
% intersection: x^2 + (mx + b)^2 = r^2
% ... x^2 + m^2x^2 + b^2 + 2mbx - r^2 = 0
% ... (1 + m^2)x^2 + 2mbx + (b^2 - r^2) = 0
A = 1 + m^2;
B = 2 * m * b;
C = b^2 - r^2;
sqrtD = sqrt(B^2 - 4*A*C);
xI = (-B+sqrtD) / (2*A);
yI = m * xI + b;
if (abs(atan2(yB - yA, xB - xA)-atan2(yI - yA, xI - xA)) > 1e-5)
xI = (-B-sqrtD) / (2*A);
yI = m * xI + b;
end
Remark #1: I didn't check the delta for being negative, since you said one point is inside the circle and the other is outside of it.
Remark #2: You need to cover the special case where A == B.
Remark #3: You need to cover the special case where xA == xB.
Remark #4: You can pick the correct answer with much less cost than finding the slope of two vectors, calculating the absolute variance between them and comparing the result with an epsilon! :)

Finding coordinates of Hexagonal path

I am trying to convert a movement along a straight line ( 2 points) to a movement along Hexagonal path, I tried different formula and did not work.
I would like to find out the coordinates of P,Q,R,M based on A and B.
I hope someone suggest a better formula which gives me the coordinates to move a long Hexagonal path.
If you are familiar with complex numbers (and assuming this is a regular hexagon),
D = B - A
P = A + D( 1 + sqrt(3)i )/4
Q = A + D( 3 + sqrt(3)i )/4
R = A + D( 1 - sqrt(3)i )/4
M = A + D( 3 - sqrt(3)i )/4
EDIT:
If you are not familiar with complex numbers, we should not attempt to use them here. They are a wonderful tool, but not easy to grasp at first. Let's do it the long way:
A = (Ax, Ay)
B = (Bx, By)
D = B - A = (Dx, Dy) where Dx=Ax-Bx and Dy=Ay-By
P = (Ax + Dx/4 - sqrt(3)Dy/4, Ay + Dy/4 + sqrt(3)Dx/4)
Q = (Ax + 3Dx/4 - sqrt(3)Dy/4, Ay + 3Dy/4 + sqrt(3)Dx/4)
R = (Ax + Dx/4 + sqrt(3)Dy/4, Ay + Dy/4 - sqrt(3)Dx/4)
M = (Ax + 3Dx/4 + sqrt(3)Dy/4, Ay + 3Dy/4 - sqrt(3)Dx/4)
This is easier to conceptualize if you imagine your hexagon as being made up of vectors - lines with a magnitude (distance) and a direction (angle from the west-to-east horizon rotating counterclockwise).
Call the vector from A to B D. If you use some trigonometry to figure out the geometry of a hexagon, D's magnitude is two times the length of the side of the hexagon. So, we can use this to construct vectors that are as large as our other hexagon sides, and thereby get the hexagon's other points.
Take the vector D, halve its magnitude, rotate it 60 degrees ccw and add this new vector to A's position. This gives you P.
Do the same thing but rotate it 60 degrees cw and add this to A's position. This gives you R.
Similarly, Q is the vector D halved, rotated 60 degrees cw, inverted and added to B's position.
Finally, M is the vector D halved, rotated 60 degrees ccw, inverted and added to B's position.
(To convert a vector into x distance moved and y distance moved, multiply the magnitude by the cos of the angle and by the sin of the angle respectively. Make sure you are using radians if radians are needed and degrees if degrees are needed.)

Distance between 2 points in a circle

I am given 2 points inside a circle. I have to find a point on the circle (not inside, not outside) so that the sum of the distances between the given 2 points and the point i found is minimum. I only have to find the minimum distance, not the position of the point.
It is a minimization problem:
minimize sqrt((x1-x0)^2 + (y1-y0)^2) + sqrt((x2-x0)^2 + (y2-y0)^2)
^ ^
(distance from point1) (distance from point 2)
subject to constraints:
x1 = C1
y1 = C2
x2 = C3
x4 = C4
x0^2 + y0^2 = r^2
(assuming the coordinates are already aligned to the center of the circle as (0,0)).
(C1,C2,C3,C4,r) are given constants, just need to assign them.
After assigning x1,y1,x2,y2 - you are given a minimization problem with 2 variables (x0,y0) and a constraint. The minimization problem can be solved using lagrange multiplier.
Let (x1, y1) and (x2, y2) be the points inside the circle, (x, y) be the point on the circle, r be the radius of the circle.
Your problem reduces to a Lagrange conditional extremum problem, namely:
extremum function:
f(x, y) = sqrt((x-x1)^2 + (y-y1)^2) + sqrt((x-x2)^2 + (y-y2)^2)
condition:
g(x, y) = x^2 + y^2 = r^2 (1)
Introduce an auxiliary function(reference):
Λ(x, y, λ) = f(x, y) + λ(g(x, y) - r^2)
Let ∂Λ / ∂x = 0, we have:
(x-x1)/sqrt((x-x1)^2 + (y-y1)^2) + (x-x2)/sqrt((x-x2)^2 + (y-y2)^2) + 2λx = 0 (2)
Let ∂Λ / ∂y = 0, we have:
(y-y1)/sqrt((x-x1)^2 + (y-y1)^2) + (y-y2)/sqrt((x-x2)^2 + (y-y2)^2) + 2λy = 0 (3)
Now we have 3 variables(i.e. x, y and λ) and 3 equations(i.e. (1), (2) and (3)), so it's solvable.
Please be noted that there should be two solutions(unless two inside points happen to be the center of the circle). One is the minimal value(which is what you need), the other is the maximal value(which will be ignored).
just another approach(which is more directly):
for simplicity, assume the circle is at (0,0) with radius r
and suppose two points are P1(x1,y1) and P2(x2,y2)
we can calculate the polar angle of these two points, suppose they are alpha1 and alpha2
obviously, the point which is on the circle and having the minimum sum of distance to P1 and P2 is within the circular sector composed of alpha1 and alpha2
meanwhile, the sum of distance between the point on the circle within that sector and P1 and P2 is a quadratic function. so, the minimum distance can be found by using trichotomy.

Line Passing Through Given Points

I am trying to find the angle of the outer line of the object in the green region of the image as shown in the image above…
For that, I have scanned the green region and get the points (dark blue points as shown in the image)...
As you can see, the points are not making straight line so I can’t find angle easily.
So I think I have to find a middle way and
that is to find the line so that the distance between each point and line remain as minimum as possible.
So how can I find the line so that each point exposes minimum distance to it……?
Is there any algorithm for this or is there any good way other than this?
The obvious route would be to do a least-squares linear regression through the points.
The standard least squares regression formulae for x on y or y on x assume there is no error in one coordinate and minimize the deviations in the coordinate from the line.
However, it is perfectly possible to set up a least squares calculation such that the value minimized is the sum of squares of the perpendicular distances of the points from the lines. I'm not sure whether I can locate the notebooks where I did the mathematics - it was over twenty years ago - but I did find the code I wrote at the time to implement the algorithm.
With:
n = ∑ 1
sx = ∑ x
sx2 = ∑ x2
sy = ∑ y
sy2 = ∑ y2
sxy = ∑ x·y
You can calculate the variances of x and y and the covariance:
vx = sx2 - ((sx * sx) / n)
vy = sy2 - ((sy * sy) / n)
vxy = sxy - ((sx * sy) / n)
Now, if the covariance is 0, then there is no semblance of a line. Otherwise, the slope and intercept can be found from:
slope = quad((vx - vy) / vxy, vxy)
intcpt = (sy - slope * sx) / n
Where quad() is a function that calculates the root of quadratic equation x2 + b·x - 1 with the same sign as c. In C, that would be:
double quad(double b, double c)
{
double b1;
double q;
b1 = sqrt(b * b + 4.0);
if (c < 0.0)
q = -(b1 + b) / 2;
else
q = (b1 - b) / 2;
return (q);
}
From there, you can find the angle of your line easily enough.
Obviously the line will pass through averaged point (x_average,y_average).
For direction you may use the following algorithm (derived directly from minimizing average square distance between line and points):
dx[i]=x[i]-x_average;
dy[i]=y[i]-y_average;
a=sum(dx[i]^2-dy[i]^2);
b=sum(2*dx[i]*dy[i]);
direction=atan2(b,a);
Usual linear regression will not work here, because it assumes that variables are not symmetric - one depends on other, so if you will swap x and y, you will have another solution.
The hough transform might be also a good option:
http://en.wikipedia.org/wiki/Hough_transform
You might try searching for "total least squares", or "least orthogonal distance" but when I tried that I saw nothing immediately applicable.
Anyway suppose you have points x[],y[], and the line is represented by a*x+b*y+c = 0, where hypot(a,b) = 1. The least orthogonal distance line is the one that minimises Sum{ (a*x[i]+b*y[i]+c)^2}. Some algebra shows that:
c is -(a*X+b*Y) where X is the mean of the x's and Y the mean of the y's.
(a,b) is the eigenvector of C corresponding to it's smaller eigenvalue, where C is the covariance matrix of the x's and y's

Testing whether a line segment intersects a sphere

I am trying to determine whether a line segment (i.e. between two points) intersects a sphere. I am not interested in the position of the intersection, just whether or not the segment intersects the sphere surface. Does anyone have any suggestions as to what the most efficient algorithm for this would be? (I'm wondering if there are any algorithms that are simpler than the usual ray-sphere intersection algorithms, since I'm not interested in the intersection position)
If you are only interested if knowing if it intersects or not then your basic algorithm will look like this...
Consider you have the vector of your ray line, A -> B.
You know that the shortest distance between this vector and the centre of the sphere occurs at the intersection of your ray vector and a vector which is at 90 degrees to this which passes through the centre of the sphere.
You hence have two vectors, the equations of which fully completely defined. You can work out the intersection point of the vectors using linear algebra, and hence the length of the line (or more efficiently the square of the length of the line) and test if this is less than the radius (or the square of the radius) of your sphere.
I don't know what the standard way of doing it is, but if you only want to know IF it intersects, here is what I would do.
General rule ... avoid doing sqrt() or other costly operations. When possible, deal with the square of the radius.
Determine if the starting point is inside the radius of the sphere. If you know that this is never the case, then skip this step. If you are inside, your ray will intersect the sphere.
From here on, your starting point is outside the sphere.
Now, imagine the small box that will fit sphere. If you are outside that box, check the x-direction, y-direction and z-direction of the ray to see if it will intersect the side of the box that your ray starts at. This should be a simple sign check, or comparison against zero. If you are outside the and moving away from it, you will never intersect it.
From here on, you are in the more complicated phase. Your starting point is between the imaginary box and the sphere. You can get a simplified expression using calculus and geometry.
The gist of what you want to do is determine if the shortest distance between your ray and the sphere is less than radius of the sphere.
Let your ray be represented by (x0 + it, y0 + jt, z0 + kt), and the centre of your sphere be at (xS, yS, zS). So, we want to find t such that it would give the shortest of (xS - x0 - it, yS - y0 - jt, zS - z0 - kt).
Let x = xS - x0, y = yX - y0, z = zS - z0, D = magnitude of the vector squared
D = x^2 -2*xit + (i*t)^2 + y^2 - 2*yjt + (j*t)^2 + z^2 - 2*zkt + (k*t)^2
D = (i^2 + j^2 + k^2)t^2 - (xi + yj + zk)*2*t + (x^2 + y^2 + z^2)
dD/dt = 0 = 2*t*(i^2 + j^2 + k^2) - 2*(xi + yj + z*k)
t = (xi + yj + z*k) / (i^2 + j^2 + k^2)
Plug t back into the equation for D = .... If the result is less than or equal the square of the sphere's radius, you have an intersection. If it is greater, then there is no intersection.
This page has an exact solution for this problem. Essentially, you are substituting the equation for the line into the equation for the sphere, then computes the discriminant of the resulting quadratic. The values of the discriminant indicate intersection.
Are you still looking for an answer 13 years later? Here is a complete and simple solution
Assume the following:
the line segment is defined by endpoints as 3D vectors v1 and v2
the sphere is centered at vc with radius r
Ne define the three side lengths of a triangle ABC as:
A = v1-vc
B = v2-vc
C = v1-v2
If |A| < r or |B| < r, then we're done; the line segment intersects the sphere
After doing the check above, if the angle between A and B is acute, then we're done; the line segment does not intersect the sphere.
If neither of these conditions are met, then the line segment may or may not intersect the sphere. To find out, we just need to find H, which is the height of the triangle ABC taking C as the base. First we need φ, the angle between A and C:
φ = arccos( dot(A,C) / (|A||C|) )
and then solve for H:
sin(φ) = H/|A|
===> H = |A|sin(φ) = |A| sqrt(1 - (dot(A,C) / (|A||C|))^2)
and we are done. The result is
if H < r, then the line segment intersects the sphere
if H = r, then the line segment is tangent to the sphere
if H > r, then the line segment does not intersect the sphere
Here that is in Python:
import numpy as np
def unit_projection(v1, v2):
'''takes the dot product between v1, v2 after normalization'''
u1 = v1 / np.linalg.norm(v1)
u2 = v2 / np.linalg.norm(v2)
return np.dot(u1, u2)
def angle_between(v1, v2):
'''computes the angle between vectors v1 and v2'''
return np.arccos(np.clip(unit_projection(v1, v2), -1, 1))
def check_intersects_sphere(xa, ya, za, xb, yb, zb, xc, yc, zc, radius):
'''checks if a line segment intersects a sphere'''
v1 = np.array([xa, ya, za])
v2 = np.array([xb, yb, zb])
vc = np.array([xc, yc, zc])
A = v1 - vc
B = v2 - vc
C = v1 - v2
if(np.linalg.norm(A) < radius or np.linalg.norm(B) < radius):
return True
if(angle_between(A, B) < np.pi/2):
return False
H = np.linalg.norm(A) * np.sqrt(1 - unit_projection(A, C)**2)
if(H < radius):
return True
if(H >= radius):
return False
Note that I have written this so that it returns False when either endpoint is on the surface of the sphere, or when the line segment is tangent to the sphere, because it serves my purposes better.
This might be essentially what user Cruachan suggested. A comment there suggests that other answers are "too elaborate". There might be a more elegant way to implement this that uses more compact linear algebra operations and identities, but I suspect that the amount of actual compute required boils down to something like this. If someone sees somewhere to save some effort please do let us know.
Here is a test of the code. The figure below shows several trial line segments originating from a position (-1, 1, 1) , with a unit sphere at (1,1,1). Blue line segments have intersected, red have not.
And here is another figure which verifies that line segments that stop just short of the sphere's surface do not intersect, even if the infinite ray that they belong to does:
Here is the code that generates the image:
import matplotlib.pyplot as plt
radius = 1
xc, yc, zc = 1, 1, 1
xa, ya, za = xc-2, yc, zc
nx, ny, nz = 4, 4, 4
xx = np.linspace(xc-2, xc+2, nx)
yy = np.linspace(yc-2, yc+2, ny)
zz = np.linspace(zc-2, zc+2, nz)
n = nx * ny * nz
XX, YY, ZZ = np.meshgrid(xx, yy, zz)
xb, yb, zb = np.ravel(XX), np.ravel(YY), np.ravel(ZZ)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for i in range(n):
if(xb[i] == xa): continue
intersects = check_intersects_sphere(xa, ya, za, xb[i], yb[i], zb[i], xc, yc, zc, radius)
color = ['r', 'b'][int(intersects)]
s = [0.3, 0.7][int(intersects)]
ax.plot([xa, xb[i]], [ya, yb[i]], [za, zb[i]], '-o', color=color, ms=s, lw=s, alpha=s/0.7)
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
x = np.outer(np.cos(u), np.sin(v)) + xc
y = np.outer(np.sin(u), np.sin(v)) + yc
z = np.outer(np.ones(np.size(u)), np.cos(v)) + zc
ax.plot_surface(x, y, z, rstride=4, cstride=4, color='k', linewidth=0, alpha=0.25, zorder=0)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.tight_layout()
plt.show()
you sorta have to work that the position anyway if you want accuracy. The only way to improve speed algorithmically is to switch from ray-sphere intersection to ray-bounding-box intersection.
Or you could go deeper and try and improve sqrt and other inner function calls
http://wiki.cgsociety.org/index.php/Ray_Sphere_Intersection

Resources