Transfer coordinates to a new system - image

I would like to convert a point coordinates to a new generated coordinate system
the original system start in the top left corner of the image (0,0)
The information that I have in a new system are :
1- I have the value of the new original (x0,y0) in some where in the image
2- also I have 2 points on both new axes ( 4 points in total 2 in each line)
using this I can calculate the line equation for the 2 lines of axes (y=a1x+b1) ,(y=a2x+b2)
3- I have vector for each line (Vx, Vy)
Note: sometime the new axes rotate (the lines are not exactly horizontal or vertical)
How can I convert the points coordinates to this new system
any help will be so appreciated
here is the image

First express your lines like a1*(x-x0)+b1*(y-y0)=0 and a2*(x-x0)+b2*(y-y0)=0 and their intersection x0,y0 is accounted for already in the equations.
updated signs
The transformation from x,y to z,w is
z = -sqrt(a1^2+b1^2)*(a2*(x-x0)+b2*(y-y0))/(a2*b1-a1*b2)
w = sqrt(a2^2+b2^2)*(a1*(x-x0)+b1*(y-y0))/(a1*b2-a2*b1)
and the inverse
x = x0 - b1*z/sqrt(a1^2+b1^2) + b2*w/sqrt(a2^2+b2^2)
y = y0 + a1*z/sqrt(a1^2+b1^2) - a2*w/sqrt(a2^2+b2^2)
It would be helpful to scale the coefficients such that sqrt(a1^2+b1^2)=1 and sqrt(a2^2+b2^2)=1.
Note that this works for non-orthogonal lines also. As long as they are not parallel and a2*b1-a1*b2!=0 it is going to work.
Example
The z line (-2)*(x-3) + (1)*(y-1) = 0 and w line (-1)*(x-3) + (-4)*(y-1) = 0 meet at (3,1). The coefficients are thus a1=-2, b1=1, a2=-1, b2=-4.
The coordinates (x,y)=(2,1) transform to
z = -sqrt((-2)^2+1^2) ((-1) (x-3)+(-4) (y-1))/((-1) 1-(-2) (-4)) = 0.2484
w = sqrt((-1)^2+(-4)^2) ((-2) (x-3)+1 (y-1))/((-2) (-4)-(-1) 1) = 0.9162
With the inverse
x = -1 z/sqrt((-2)^2+1^2)+(-4) w/sqrt((-1)^2+(-4)^2)+3 = 2
y = (-2) z/sqrt((-2)^2+1^2)-(-1) w/sqrt((-1)^2+(-4)^2)+1 = 1
Development
For a line a1*(x-x0)+b1*(y-y0)=0 the direction vector along the line is e1 = [e1x,e1y]= [-b1/sqrt(a1^2+b1^2),a1/sqrt(a1^2+b1^2)]. Similarly for the other line.
The screen coordinates of a local point [z,w] is found by starting at the origin x0, y0 and moving by z along the first line and then by w along the second line. So
x = x0 + e1x*z + e2x*w = x0 -b1/sqrt(a1^2+b1^2)*z - b2/sqrt(a2^2+b2^2)*w
y = y0 + e1y*z + e2y*w = y0 +a1/sqrt(a1^2+b1^2)*z + a2/sqrt(a2^2+b2^2)*w
Now I need to flip the direction of the second line to make it work per the original posting visualization, by reversing the sign of w.
To find z, w from x, y invert the above two equations.

Related

Algorithm to get all zeniths crossing a box in three dimensions, MATLAB implementation

I have a 3D geometry problem and I am not certain of the best approach to solve it. I have a model with two boxes, one above the others. They have the same dimension, L (length) * p (depth) * e (thickness), and are separated by a height of h. They are perfectly superposed, with no offset between them.
For each point of my bottom box, I want to get the zenith of all lines that can cross the top box and arrive to this point. It doesn't matter if the line crosses the top box by the top or the side.
The zenith is the angle of "looking up". In our case, a zenith of 0 represents the point directly above the point P, and an angle of 90 is directly looking in front. A zenith of 180 would be looking below the point, but for our use, it's useless. The zeniths we look for are between 0 and 90°.
For a more intuitive visualization, let's say that I have a hole in the ceiling, and that I want to map the zenith of all light that crosses this hole and reaches the floor.
This is what it looks like:
For any point P of the bottom box, I want an array containing the zeniths of all "rays" that cross the top box before arriving on P. The red lines are the "edges", the last zeniths I would get for each corner.
I am working on a way to code it in MATLAB and I was wondering if there was a better algorithm that I am not seeing. My approach, in pseudocode, would be this:
bottomBox = [1:L, 1:p, 1:e];
topBox = [1:L, 1:p, 1+h:e+h];
results = zeros(L:p) * NaN; % Array of results, one per "case" on the bottom box
zeniths = zeros(L:p) * NaN; % Array of zeniths for each result case
for i = 1:L
for j = 1:p % Browsing the bottom box case by case
for k = 1:L
for l = 1:p
for m = 1:e % For each bottom box case, browsing the top box case by case
p1 = topBox(k,l,m); % p1 is each case on the top box
p2 = bottomBox(i,j,1); % p2 is the current bottom box case, z doesn't mattter
p3 = topBox(i,j,m); % p3 is the projection of p2 on the top box (zenith = 0)
v1 = p1 - p2;
v2 = p3 - p2;
zeniths(k,l) = rad2deg(atan2(norm(cross(p1, p2)), dot(p1, p2)));
end
end
end
results(i,j) = zeniths;
end
end
I tried to implement this and I couldn't get it to work. More specifically, the angle calculation doesn't seem to work, I have an error stating:
Error using cross;
A and B must be of length 3 in the dimension in which the cross product is taken.
I am looking for advice on how to build the algorithm.
Please tell me if the question is better suited for another StackExchange community, such as Math.
I'll get you started showing you one way to do it for 1 point and I'll let you build the final loop to do the calc for all your points.
As expressed in the comment, for the purpose of these calculations, you do not need to consider the thickness of your plates, you can model them simply with two parallel planes separated by a distance H.
I don't know the size of your plates nor the grid size you want so I'll keep it simple for this example:
H = 5 ; % distance between the planes
[X,Y] = meshgrid(-3:3,-2:2) ;
GridSize = size(X) ;
Zb = zeros(GridSize) ;
Zt = zeros(GridSize) + H ;
This gives you 4 matrices, defining 2 planes. The bottom plane is composed of [X,Y,Zb] and the top plane is formed by [X,Y,Zt].
If you want to visualise them, you can run the following code (optional):
%% Display planes
figure ;
ht = surf(X,Y,Zt, 'FaceColor',[.8 .8 .8],'DisplayName','Top plate') ;
hold on
hb = surf(X,Y,Zb, 'FaceColor',[.6 .6 .6],'DisplayName','Bottom plate') ;
xlabel('X') ; ylabel('Y') ; zlabel('Z') ;
axis equal ; legend show
Now for the rest of the example, I selected a point P, at coordinate [-2,1,0]. This choice is completely arbitrary, just for the example. In your final algorythm you will still have to loop over several points Pi (although remember that your problem is symetric so if your domain is too large you can reduce your computations by using the symetries of your model).
%% This will have to be embedded into a loop over the points Pi
% Assuming points P=(-2,1,0)
p = [-2;1;0] ;
zn = [0;0;1] ; % unitary vector, oriented Oz
dx = X - p(1) ; % `x` distance between all points of the plane and P
dy = Y - p(2) ; % `y` distance between all points of the plane and P
dz = zeros(size(X)) + H ; % `z` distance (all the same)
V = [dx(:) dy(:) dz(:)].' ; % to obtain list of vector V = [dx;dy;dz] ;
nv = size(V,2) ; % number of points/angle to calculate
zenith = zeros(nv,1) ; % preallocate result matrix (always good!)
for k=1:nv
% [u] is the vector going from `P` to the current point considered on the top plane
u = V(:,k) ;
% determine the angle between [u] and [zn]
zenith(k) = atan2( norm(cross(u,zn)) , dot(u,zn) ) ;
end
% Reshape "zenith" from vector to matrix so it matches the base grid system
zenith = reshape( zenith , GridSize ) ;
You now have, for this point P, a matrix of angle with every other point of the top plane:
>> rad2deg(zenith)
ans =
32.31 30.96 32.31 35.80 40.32 45.00 49.39
24.09 21.80 24.09 29.50 35.80 41.81 47.12
15.79 11.31 15.79 24.09 32.31 39.51 45.56
11.31 0 11.31 21.80 30.96 38.66 45.00
15.79 11.31 15.79 24.09 32.31 39.51 45.56
Once again, completely optionally, if you want to visualise the vectors which were used for the calculations:
for k=1:nv
hp(k) = plot3([p(1) X(k)],[p(2) Y(k)],[0 H],'Marker','o','MarkerFaceColor','k') ;
end
will yield:
Now for your final result, remember you have a 2D matrix for each point P of your bottom plane, so your final result will either be a collection of 2D matrices or a large 3D matrix.
Zenith angle is just
atan2(h, sqrt(dx^2+dy^2))
where dx, dy are coordinate differences along L and p axes (i-k and j-l in your loops)
Perhaps h+m (m as your variable for m = 1:e) instead of h if you need points inside top box

Determine the "edge" points given the equation of the line

For a given line of an equation y = mx + c where m is the gradient and c is the y-intercept. How would I determine the "edge-points" on a graph?
To clarify what I mean by "edge-points", I've added an example below.
The edge-points are circled in red. To determine the edge-points here it would simply be (0, c) & (maximum x-value, m * maximum x-value + c). However, the problem arises when I consider lines with a different m value. For example:
I can't apply the same logic here, instead the edge-points would be ((maximum y-value - c) * m, maximum y-value) & (-c * m, 0), which was derived from the equation y = mx + c. So my question is how would I determine these 2 edge-points given any m or c? Is there a certain pattern I'm not seeing here?
You need to solve 4 simple linear equations (not equation system!):
y = m * 0 + c = c
y = m * maxX + c
0 = m * x + c
maxY = m * x + c
and get points of intersections with axes and with max lines. Then filter out points with negative coordinates and too large ones, because you want only the 1st quadrant
The first one equation is already solved y=c
The second gives point of intersection with right vertical line
The third gives point of intersection with OX axis
The fourth gives point of intersection with top horizontal line
Example:
maxX = 5
maxY = 5
line y = 2 *x - 1
x0, y0 = 0, -1
x1, y1 = 5, 9
x2, y2 = 1/2, 0
x3, y3 = 2, 5
First pair contains negative coordinate y=-1
Second pair contains y=9 > maxY
Third and fourth ones fulfill your constraints.
So this line gives segment (1/2, 0)-(2, 5) (like near vertical segment at your second picture)
This algo might be considered as simple kind of line clippping by rectangle
For the line to be in the given rectangle there is a constraint given by the x values and a constraint given by the y values.
The x constraint trivially leads to an interval in which the x values must be.
The y constraint also gives you such an interval for the x values but only after some easy calculation.
Now determine the intersection of the two intervals (which may also be empty).

How to make an "X" through circle in jython?

I have no idea how to do this. I need to draw two lines that make an X through a circle, where the starting and end points would be on the circumference of the circle. If anybody could even give me a direction to go in to do this, it'd be appreciated.
Get the maths right first.
The most general case of circle-line intersection is described here: http://mathworld.wolfram.com/Circle-LineIntersection.html
But if the center of the circle is the origin, its radius is 1, and the lines are forming an x, so a 45 degree angle with the horizontal and vertical axes, it is quite a bit more simple:
The circle is defined by
x2 + y2 = 1
The line with 45 degree slope is defined by
y = x
Their intersections are the points (x,y) where both statements are true so
x2 + x2 = 1
2 x2 = 1
x2 = 1/2
x = sqrt(1/2) or x = -sqrt(1/2) and y = x
so points (sqrt(1/2), sqrt(1/2)) and (-sqrt(1/2), -sqrt(1/2))
Same for the other line.
One line goes from (-sqrt(0.5), -sqrt(0.5)) (bottom left) to (sqrt(0.5), sqrt(0.5)) (top right) and the other from (-sqrt(0.5), sqrt(0.5)) (top left) to (sqrt(0.5), -sqrt(0.5)) (bottom right).
On Wolfram Alpha

MATLAB: Drawing a line over a black and white image

What is the best way to draw a line over a black and white (binary) image in MATLAB, provided the start and end coordinates are known?
Please note, I am not trying to add an annotation line. I would like the line to become part of the image.
You may want to look at my answer to an SO question about adding a line to an image matrix. Here's a similar example to the one I have in that answer, which will make a white line running from row and column index (10, 10) to (240, 120):
img = imread('cameraman.tif'); % Load a sample black and white image
x = [10 240]; % x coordinates
y = [10 120]; % y coordinates
nPoints = max(abs(diff(x)), abs(diff(y)))+1; % Number of points in line
rIndex = round(linspace(y(1), y(2), nPoints)); % Row indices
cIndex = round(linspace(x(1), x(2), nPoints)); % Column indices
index = sub2ind(size(img), rIndex, cIndex); % Linear indices
img(index) = 255; % Set the line points to white
imshow(img); % Display the image
And here's the resulting image:
If you are bothered by exceptional cases of other methods here's a bullet-proof method that results in a line:
whose pixels always touch each other during the whole length of the line (pixels are 8-neighbors to each other),
density of the line is not dependent on the additional parameter, but is determined flexibly to accommodate guarantee from the first point.
Inputs (convenient for making function out of this code):
img - matrix that contains image,
x1, y1, x2, y2 - coordinates of the end points of the line to be drawn.
Code:
% distances according to both axes
xn = abs(x2-x1);
yn = abs(y2-y1);
% interpolate against axis with greater distance between points;
% this guarantees statement in the under the first point!
if (xn > yn)
xc = x1 : sign(x2-x1) : x2;
yc = round( interp1([x1 x2], [y1 y2], xc, 'linear') );
else
yc = y1 : sign(y2-y1) : y2;
xc = round( interp1([y1 y2], [x1 x2], yc, 'linear') );
end
% 2-D indexes of line are saved in (xc, yc), and
% 1-D indexes are calculated here:
ind = sub2ind( size(img), yc, xc );
% draw line on the image (change value of '255' to one that you need)
img(ind) = 255;
Here's the example image with three lines drawn on it:
This algorithm offers one approach.
It actually is just a modification on plesiv's answer. I'm drawing thousands of lines over an image and I need to increase the performance. The most improvement made by omitting interp1 calls and using integer variables made it slightly faster. It performs about 18% faster on my PC comparing to plesiv's code.
function img = drawLine(img, x1, y1, x2, y2)
x1=int16(x1); x2=int16(x2); y1=int16(y1); y2=int16(y2);
% distances according to both axes
xn = double(x2-x1);
yn = double(y2-y1);
% interpolate against axis with greater distance between points;
% this guarantees statement in the under the first point!
if (abs(xn) > abs(yn))
xc = x1 : sign(xn) : x2;
if yn==0
yc = y1+zeros(1, abs(xn)+1, 'int16');
else
yc = int16(double(y1):abs(yn/xn)*sign(yn):double(y2));
end
else
yc = y1 : sign(yn) : y2;
if xn==0
xc = x1+zeros(1, abs(yn)+1, 'int16');
else
xc = int16(double(x1):abs(xn/yn)*sign(xn):double(x2));
end
end
% 2-D indexes of line are saved in (xc, yc), and
% 1-D indexes are calculated here:
ind = sub2ind(size(img), yc, xc);
% draw line on the image (change value of '255' to one that you need)
img(ind) = 255;
end
If you have the Computer Vision System Toolbox, you can use insertShape.

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