Converting Lab Values to RGB values in opencv - c++

I am trying to convert the Lab values to its corresponding RGB values.I don't want to convert Lab image to RGB image but some values of L a and b.The function cvCvtColor only works for images.Can anybody tell me how to do this.
Thanks;
Code :
CvMat* rgb = cvCreateMat(centres->rows,centres->cols,centres->type);
cvCvtColor(centres,rgb,CV_Lab2BGR);

I don't know how to do it in OpenCV, but if something else is alright I've implemented it in C. See function color_Lab_to_LinearRGB and color_LinearRGB_to_RGB.
Here's the code:
double L, a, b;
double X, Y, Z;
double R, G, B;
// Lab -> normalized XYZ (X,Y,Z are all in 0...1)
Y = L * (1.0/116.0) + 16.0/116.0;
X = a * (1.0/500.0) + Y;
Z = b * (-1.0/200.0) + Y;
X = X > 6.0/29.0 ? X * X * X : X * (108.0/841.0) - 432.0/24389.0;
Y = L > 8.0 ? Y * Y * Y : L * (27.0/24389.0);
Z = Z > 6.0/29.0 ? Z * Z * Z : Z * (108.0/841.0) - 432.0/24389.0;
// normalized XYZ -> linear sRGB (in 0...1)
R = X * (1219569.0/395920.0) + Y * (-608687.0/395920.0) + Z * (-107481.0/197960.0);
G = X * (-80960619.0/87888100.0) + Y * (82435961.0/43944050.0) + Z * (3976797.0/87888100.0);
B = X * (93813.0/1774030.0) + Y * (-180961.0/887015.0) + Z * (107481.0/93370.0);
// linear sRGB -> gamma-compressed sRGB (in 0...1)
R = R > 0.0031308 ? pow(R, 1.0 / 2.4) * 1.055 - 0.055 : R * 12.92;
G = G > 0.0031308 ? pow(G, 1.0 / 2.4) * 1.055 - 0.055 : G * 12.92;
B = B > 0.0031308 ? pow(B, 1.0 / 2.4) * 1.055 - 0.055 : B * 12.92;

I think the only way to do what you want is:
look at the OpenCV source code or documentation for cvCvtColor and implement the equations yourself (they're all explicitly given on that page)
create a dummy image with the few Lab values you want to convert (say 1 by n by 3, where n is the number of values you want to convert) and use cvCvtColor around that.

Related

how can I tell SymPy that some terms are positive then make SymPy simplify `sqrt(x^2)` to `x` where `x` may be a complicated term?

I'm solving the problem is in section Auxiliary Elements in Polya's How to Solve It:
Construct a triangle, being given one angle (A), the altitude (h) drawn from the vertex of the given angle, and the perimeter (p) of the triangle.
I get the solution below, and try to verify it by SymPy:
from sympy import *
h, p, A = symbols("h p A", positive=True)
u = sqrt(h * p * p / 2 / (h + h * cos(A) + p * sin(A)))
v = (p - u * u * sin(A) / h) / 2
y = v + sqrt(v * v - u * u)
z = v - sqrt(v * v - u * u)
x = sqrt(y * y + z * z - 2 * y * z * cos(A))
# x, y, z are solutions
# now verify them:
print("x + y + z =", simplify(x + y + z))
The expected result should be x + y + z = p but the actual output is a bit complicated:
x + y + z = (-p**2*sin(A)/2 + (4*p + 2*sqrt(p**4*sin(A)**2/(h*cos(A) + h + p*sin(A))**2))*(h*cos(A) + h + p*sin(A))/4)/(h*cos(A) + h + p*sin(A))
Here I notice that sqrt(p**4*sin(A)**2/(h*cos(A) + h + p*sin(A))**2) are not simplified to p**2*sin(A)/(h*cos(A) + h + p*sin(A)) because SymPy doesn't know whether sin(A) and h*cos(A) + h + p*sin(A) are positive.
How could I set some parameter to simplify() method to make SymPy do the reasonable simplification with some condition (e.g. some terms are positive so that sqrt() can be simplified)?
I refer Sympy - Simplify expression within domain but it doesn't seem to work.
One way to do this would be to make positive symbols for sin(A) and cos(A) e.g.:
sinA, cosA = symbols('sinA, cosA', positive=True)
You could use those while simplifying and substitute for them after.
Another way that will work for some cases is to use refine e.g.:
In [8]: res = simplify(x + y + z)
In [9]: res
Out[9]:
⎛ ⎛ │ sin(A) │ ⎞ ⎞
p⋅⎜-p⋅sin(A) + ⎜p⋅│───────────────────────│ + 2⎟⋅(h⋅cos(A) + h + p⋅sin(A))⎟
⎝ ⎝ │h⋅cos(A) + h + p⋅sin(A)│ ⎠ ⎠
───────────────────────────────────────────────────────────────────────────
2⋅(h⋅cos(A) + h + p⋅sin(A))
In [10]: refine(res, Q.positive(sin(A)) & Q.positive(cos(A)))
Out[10]:
⎛ ⎛ p⋅sin(A) ⎞ ⎞
p⋅⎜-p⋅sin(A) + ⎜─────────────────────── + 2⎟⋅(h⋅cos(A) + h + p⋅sin(A))⎟
⎝ ⎝h⋅cos(A) + h + p⋅sin(A) ⎠ ⎠
───────────────────────────────────────────────────────────────────────
2⋅(h⋅cos(A) + h + p⋅sin(A))

Polar Rose 2D offset

I'm having some trouble trying to plot a polar rose with a offset C of the equation r(theta) = cos(k*theta) + C.
I'm trying to plot this polar rose: http://en.wikipedia.org/wiki/Polar_coordinate_system#/media/File:Cartesian_to_polar.gif
The polar equation can be:
r(theta) = cos(k * theta)
or
r(theta) = sin(k * theta)
The equation of the polar rose I want to draw is:
r(theta) = 2 + sin(6 * theta)
Ok, and the parametric equations will be:
x = C + sin(k * theta) * cos(theta)
y = C + sin(k * theta) * sin(theta)
In my Canvas(drawing area), my origin is not at the center of the screen, so I need to translate the rose to it. Ok, no big deal. Another point is that I need to scale the rose for it to be visible or it will be too small, but still no problem, this explains the: 100*. Here is my code, it is on C++ btw:
for ( float t = 0; t < PI_2; t+= 0.01 )
{
r = Origin.get_x() + 100*(2+(sin(6*t) * cos(t)));
h = Origin.get_y() + 100*(2+(sin(6*t) * sin(t)));
point(r,h);
}
I know that I'm doing it wrong, because when I add the +2 which should be the C constant is not working the way I want to, It's just translating more and drawing a polar rose without an offset. How do I prevent the "extra translation" and draw it properly?
x = r cos(theta), y = r sin(theta) so your parametric equations should be x(theta) = C * cos(theta) + sin(k*theta) * cos(theta) and y(theta) = C * sin(theta) + sin(k*theta) * sin(theta). You just forgot to multiply C by cos(theta) and by sin(theta) respectively.

distance from given point to given ellipse

I have an ellipse, defined by Center Point, radiusX and radiusY, and I have a Point. I want to find the point on the ellipse that is closest to the given point. In the illustration below, that would be S1.
Now I already have code, but there is a logical error somewhere in it, and I seem to be unable to find it. I broke the problem down to the following code example:
#include <vector>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <math.h>
using namespace std;
void dostuff();
int main()
{
dostuff();
return 0;
}
typedef std::vector<cv::Point> vectorOfCvPoints;
void dostuff()
{
const double ellipseCenterX = 250;
const double ellipseCenterY = 250;
const double ellipseRadiusX = 150;
const double ellipseRadiusY = 100;
vectorOfCvPoints datapoints;
for (int i = 0; i < 360; i+=5)
{
double angle = i / 180.0 * CV_PI;
double x = ellipseRadiusX * cos(angle);
double y = ellipseRadiusY * sin(angle);
x *= 1.4;
y *= 1.4;
x += ellipseCenterX;
y += ellipseCenterY;
datapoints.push_back(cv::Point(x,y));
}
cv::Mat drawing = cv::Mat::zeros( 500, 500, CV_8UC1 );
for (int i = 0; i < datapoints.size(); i++)
{
const cv::Point & curPoint = datapoints[i];
const double curPointX = curPoint.x;
const double curPointY = curPoint.y * -1; //transform from image coordinates to geometric coordinates
double angleToEllipseCenter = atan2(curPointY - ellipseCenterY * -1, curPointX - ellipseCenterX); //ellipseCenterY * -1 for transformation to geometric coords (from image coords)
double nearestEllipseX = ellipseCenterX + ellipseRadiusX * cos(angleToEllipseCenter);
double nearestEllipseY = ellipseCenterY * -1 + ellipseRadiusY * sin(angleToEllipseCenter); //ellipseCenterY * -1 for transformation to geometric coords (from image coords)
cv::Point center(ellipseCenterX, ellipseCenterY);
cv::Size axes(ellipseRadiusX, ellipseRadiusY);
cv::ellipse(drawing, center, axes, 0, 0, 360, cv::Scalar(255));
cv::line(drawing, curPoint, cv::Point(nearestEllipseX,nearestEllipseY*-1), cv::Scalar(180));
}
cv::namedWindow( "ellipse", CV_WINDOW_AUTOSIZE );
cv::imshow( "ellipse", drawing );
cv::waitKey(0);
}
It produces the following image:
You can see that it actually finds "near" points on the ellipse, but it are not the "nearest" points. What I intentionally want is this: (excuse my poor drawing)
would you extent the lines in the last image, they would cross the center of the ellipse, but this is not the case for the lines in the previous image.
I hope you get the picture. Can anyone tell me what I am doing wrong?
Consider a bounding circle around the given point (c, d), which passes through the nearest point on the ellipse. From the diagram it is clear that the closest point is such that a line drawn from it to the given point must be perpendicular to the shared tangent of the ellipse and circle. Any other points would be outside the circle and so must be further away from the given point.
So the point you are looking for is not the intersection between the line and the ellipse, but the point (x, y) in the diagram.
Gradient of tangent:
Gradient of line:
Condition for perpedicular lines - product of gradients = -1:
When rearranged and substituted into the equation of your ellipse...
...this will give two nasty quartic (4th-degree polynomial) equations in terms of either x or y. AFAIK there are no general analytical (exact algebraic) methods to solve them. You could try an iterative method - look up the Newton-Raphson iterative root-finding algorithm.
Take a look at this very good paper on the subject:
http://www.spaceroots.org/documents/distance/distance-to-ellipse.pdf
Sorry for the incomplete answer - I totally blame the laws of mathematics and nature...
EDIT: oops, i seem to have a and b the wrong way round in the diagram xD
There is a relatively simple numerical method with better convergence than Newtons Method. I have a blog post about why it works http://wet-robots.ghost.io/simple-method-for-distance-to-ellipse/
This implementation works without any trig functions:
def solve(semi_major, semi_minor, p):
px = abs(p[0])
py = abs(p[1])
tx = 0.707
ty = 0.707
a = semi_major
b = semi_minor
for x in range(0, 3):
x = a * tx
y = b * ty
ex = (a*a - b*b) * tx**3 / a
ey = (b*b - a*a) * ty**3 / b
rx = x - ex
ry = y - ey
qx = px - ex
qy = py - ey
r = math.hypot(ry, rx)
q = math.hypot(qy, qx)
tx = min(1, max(0, (qx * r / q + ex) / a))
ty = min(1, max(0, (qy * r / q + ey) / b))
t = math.hypot(ty, tx)
tx /= t
ty /= t
return (math.copysign(a * tx, p[0]), math.copysign(b * ty, p[1]))
Credit to Adrian Stephens for the Trig-Free Optimization.
Here is the code translated to C# implemented from this paper to solve for the ellipse:
http://www.geometrictools.com/Documentation/DistancePointEllipseEllipsoid.pdf
Note that this code is untested - if you find any errors let me know.
//Pseudocode for robustly computing the closest ellipse point and distance to a query point. It
//is required that e0 >= e1 > 0, y0 >= 0, and y1 >= 0.
//e0,e1 = ellipse dimension 0 and 1, where 0 is greater and both are positive.
//y0,y1 = initial point on ellipse axis (center of ellipse is 0,0)
//x0,x1 = intersection point
double GetRoot ( double r0 , double z0 , double z1 , double g )
{
double n0 = r0*z0;
double s0 = z1 - 1;
double s1 = ( g < 0 ? 0 : Math.Sqrt(n0*n0+z1*z1) - 1 ) ;
double s = 0;
for ( int i = 0; i < maxIter; ++i ){
s = ( s0 + s1 ) / 2 ;
if ( s == s0 || s == s1 ) {break; }
double ratio0 = n0 /( s + r0 );
double ratio1 = z1 /( s + 1 );
g = ratio0*ratio0 + ratio1*ratio1 - 1 ;
if (g > 0) {s0 = s;} else if (g < 0) {s1 = s ;} else {break ;}
}
return s;
}
double DistancePointEllipse( double e0 , double e1 , double y0 , double y1 , out double x0 , out double x1)
{
double distance;
if ( y1 > 0){
if ( y0 > 0){
double z0 = y0 / e0;
double z1 = y1 / e1;
double g = z0*z0+z1*z1 - 1;
if ( g != 0){
double r0 = (e0/e1)*(e0/e1);
double sbar = GetRoot(r0 , z0 , z1 , g);
x0 = r0 * y0 /( sbar + r0 );
x1 = y1 /( sbar + 1 );
distance = Math.Sqrt( (x0-y0)*(x0-y0) + (x1-y1)*(x1-y1) );
}else{
x0 = y0;
x1 = y1;
distance = 0;
}
}
else // y0 == 0
x0 = 0 ; x1 = e1 ; distance = Math.Abs( y1 - e1 );
}else{ // y1 == 0
double numer0 = e0*y0 , denom0 = e0*e0 - e1*e1;
if ( numer0 < denom0 ){
double xde0 = numer0/denom0;
x0 = e0*xde0 ; x1 = e1*Math.Sqrt(1 - xde0*xde0 );
distance = Math.Sqrt( (x0-y0)*(x0-y0) + x1*x1 );
}else{
x0 = e0;
x1 = 0;
distance = Math.Abs( y0 - e0 );
}
}
return distance;
}
The following python code implements the equations described at "Distance from a Point to an Ellipse" and uses newton's method to find the roots and from that the closest point on the ellipse to the point.
Unfortunately, as can be seen from the example, it seems to only be accurate outside the ellipse. Within the ellipse weird things happen.
from math import sin, cos, atan2, pi, fabs
def ellipe_tan_dot(rx, ry, px, py, theta):
'''Dot product of the equation of the line formed by the point
with another point on the ellipse's boundary and the tangent of the ellipse
at that point on the boundary.
'''
return ((rx ** 2 - ry ** 2) * cos(theta) * sin(theta) -
px * rx * sin(theta) + py * ry * cos(theta))
def ellipe_tan_dot_derivative(rx, ry, px, py, theta):
'''The derivative of ellipe_tan_dot.
'''
return ((rx ** 2 - ry ** 2) * (cos(theta) ** 2 - sin(theta) ** 2) -
px * rx * cos(theta) - py * ry * sin(theta))
def estimate_distance(x, y, rx, ry, x0=0, y0=0, angle=0, error=1e-5):
'''Given a point (x, y), and an ellipse with major - minor axis (rx, ry),
its center at (x0, y0), and with a counter clockwise rotation of
`angle` degrees, will return the distance between the ellipse and the
closest point on the ellipses boundary.
'''
x -= x0
y -= y0
if angle:
# rotate the points onto an ellipse whose rx, and ry lay on the x, y
# axis
angle = -pi / 180. * angle
x, y = x * cos(angle) - y * sin(angle), x * sin(angle) + y * cos(angle)
theta = atan2(rx * y, ry * x)
while fabs(ellipe_tan_dot(rx, ry, x, y, theta)) > error:
theta -= ellipe_tan_dot(
rx, ry, x, y, theta) / \
ellipe_tan_dot_derivative(rx, ry, x, y, theta)
px, py = rx * cos(theta), ry * sin(theta)
return ((x - px) ** 2 + (y - py) ** 2) ** .5
Here's an example:
rx, ry = 12, 35 # major, minor ellipse axis
x0 = y0 = 50 # center point of the ellipse
angle = 45 # ellipse's rotation counter clockwise
sx, sy = s = 100, 100 # size of the canvas background
dist = np.zeros(s)
for x in range(sx):
for y in range(sy):
dist[x, y] = estimate_distance(x, y, rx, ry, x0, y0, angle)
plt.imshow(dist.T, extent=(0, sx, 0, sy), origin="lower")
plt.colorbar()
ax = plt.gca()
ellipse = Ellipse(xy=(x0, y0), width=2 * rx, height=2 * ry, angle=angle,
edgecolor='r', fc='None', linestyle='dashed')
ax.add_patch(ellipse)
plt.show()
Which generates an ellipse and the distance from the boundary of the ellipse as a heat map. As can be seen, at the boundary the distance is zero (deep blue).
Given an ellipse E in parametric form and a point P
the square of the distance between P and E(t) is
The minimum must satisfy
Using the trigonometric identities
and substituting
yields the following quartic equation:
Here's an example C function that solves the quartic directly and computes sin(t) and cos(t) for the nearest point on the ellipse:
void nearest(double a, double b, double x, double y, double *ecos_ret, double *esin_ret) {
double ax = fabs(a*x);
double by = fabs(b*y);
double r = b*b - a*a;
double c, d;
int switched = 0;
if (ax <= by) {
if (by == 0) {
if (r >= 0) { *ecos_ret = 1; *esin_ret = 0; }
else { *ecos_ret = 0; *esin_ret = 1; }
return;
}
c = (ax - r) / by;
d = (ax + r) / by;
} else {
c = (by + r) / ax;
d = (by - r) / ax;
switched = 1;
}
double cc = c*c;
double D0 = 12*(c*d + 1); // *-4
double D1 = 54*(d*d - cc); // *4
double D = D1*D1 + D0*D0*D0; // *16
double St;
if (D < 0) {
double t = sqrt(-D0); // *2
double phi = acos(D1 / (t*t*t));
St = 2*t*cos((1.0/3)*phi); // *2
} else {
double Q = cbrt(D1 + sqrt(D)); // *2
St = Q - D0 / Q; // *2
}
double p = 3*cc; // *-2
double SS = (1.0/3)*(p + St); // *4
double S = sqrt(SS); // *2
double q = 2*cc*c + 4*d; // *2
double l = sqrt(p - SS + q / S) - S - c; // *2
double ll = l*l; // *4
double ll4 = ll + 4; // *4
double esin = (4*l) / ll4;
double ecos = (4 - ll) / ll4;
if (switched) {
double t = esin;
esin = ecos;
ecos = t;
}
*ecos_ret = copysign(ecos, a*x);
*esin_ret = copysign(esin, b*y);
}
Try it online!
You just need to calculate the intersection of the line [P1,P0] to your elipse which is S1.
If the line equeation is:
and the elipse equesion is:
than the values of S1 will be:
Now you just need to calculate the distance between S1 to P1 , the formula (for A,B points) is:
I've solved the distance issue via focal points.
For every point on the ellipse
r1 + r2 = 2*a0
where
r1 - Euclidean distance from the given point to focal point 1
r2 - Euclidean distance from the given point to focal point 2
a0 - semimajor axis length
I can also calculate the r1 and r2 for any given point which gives me another ellipse that this point lies on that is concentric to the given ellipse. So the distance is
d = Abs((r1 + r2) / 2 - a0)
As propposed by user3235832
you shall solve quartic equation to find the normal to the ellipse (https://www.mathpages.com/home/kmath505/kmath505.htm). With good initial value only few iterations are needed (I use it myself). As an initial value I use S1 from your picture.
The fastest method I guess is
http://wwwf.imperial.ac.uk/~rn/distance2ellipse.pdf
Which has been mentioned also by Matt but as he found out the method doesn't work very well inside of ellipse.
The problem is the theta initialization.
I proposed an stable initialization:
Find the intersection of ellipse and horizontal line passing the point.
Find the other intersection using vertical line.
Choose the one that is closer the point.
Calculate the initial angle based on that point.
I got good results with no issue inside and outside:
As you can see in the following image it just iterated about 3 times to reach 1e-8. Close to axis it is 1 iteration.
The C++ code is here:
double initialAngle(double a, double b, double x, double y) {
auto abs_x = fabs(x);
auto abs_y = fabs(y);
bool isOutside = false;
if (abs_x > a || abs_y > b) isOutside = true;
double xd, yd;
if (!isOutside) {
xd = sqrt((1.0 - y * y / (b * b)) * (a * a));
if (abs_x > xd)
isOutside = true;
else {
yd = sqrt((1.0 - x * x / (a * a)) * (b * b));
if (abs_y > yd)
isOutside = true;
}
}
double t;
if (isOutside)
t = atan2(a * y, b * x); //The point is outside of ellipse
else {
//The point is inside
if (xd < yd) {
if (x < 0) xd = -xd;
t = atan2(y, xd);
}
else {
if (y < 0) yd = -yd;
t = atan2(yd, x);
}
}
return t;
}
double distanceToElipse(double a, double b, double x, double y, int maxIter = 10, double maxError = 1e-5) {
//std::cout <<"p="<< x << "," << y << std::endl;
auto a2mb2 = a * a - b * b;
double t = initialAngle(a, b, x, y);
auto ct = cos(t);
auto st = sin(t);
int i;
double err;
for (i = 0; i < maxIter; i++) {
auto f = a2mb2 * ct * st - x * a * st + y * b * ct;
auto fp = a2mb2 * (ct * ct - st * st) - x * a * ct - y * b * st;
auto t2 = t - f / fp;
err = fabs(t2 - t);
//std::cout << i + 1 << " " << err << std::endl;
t = t2;
ct = cos(t);
st = sin(t);
if (err < maxError) break;
}
auto dx = a * ct - x;
auto dy = b * st - y;
//std::cout << a * ct << "," << b * st << std::endl;
return sqrt(dx * dx + dy * dy);
}

whats best way to start solving by iteration?

I am working on a home project where I need to closely solve an equation by iteration.
M = E - e* sin(E) or another way (E - e*sin(E))/M = 1.
M is previously solved for and e is given in the data message.
So would you plug in a number for E and check to see how close the value ends up to 1, then continue to adjust the plug in value of E untill the expression is within a set value to 1.00000?
Is there an "ideal" method to solving something like this in software?
The rest of my calculation function is shown as
FP64 is defined as double
bool SV_pos_GAL_L1(int chan, FP64* x, FP64* y, FP64* z) //finds SV ECEF position in orbit at ref GAL system time
{
FP64 smaxis = pow(GALChannel[chan].L1galData.sqrrtA, 2); //semi major axis
FP64 nc = sqrt( MU/(pow(smaxis, 3)) ) + GALChannel[chan].L1galData.delta_n; //n corrected
FP64 Tk = GALChannel[chan].L1galData.TOW - GALChannel[chan].L1galData.Toe; //time since ephemeris
FP64 M = GALChannel[chan].L1galData.M0 + nc * Tk; //mean anomaly
FP64 E;
FP64 v = atan( ((sqrt(1-pow(GALChannel[chan].L1galData.e,2)) * sin(E)) / (1-(GALChannel[chan].L1galData.e*cos(E)))) / ((cos(E)-GALChannel[chan].L1galData.e) / (1-(cos(E)*GALChannel[chan].L1galData.e))) );//true anomaly
FP64 Omega = GALChannel[chan].L1galData.Omega0 + (Tk * (GALChannel[chan].L1galData.dot_Omega - GALChannel[chan].L1galData.w)) - ( GALChannel[chan].L1galData.w * GALChannel[chan].L1galData.Toe); //corrected longitude of ascinding node
FP64 ArgLat = v + Omega; //argument of latitude
FP64 Su = (GALChannel[chan].L1galData.Cus * sin(2*ArgLat)) + ( GALChannel[chan].L1galData.Cuc * cos(2*ArgLat)); //argument of latitude correction
FP64 Sr = (GALChannel[chan].L1galData.Crs * sin(2*ArgLat)) + ( GALChannel[chan].L1galData.Crc * cos(2*ArgLat)); //radius correction
FP64 Si = (GALChannel[chan].L1galData.Cis * sin(2*ArgLat)) + ( GALChannel[chan].L1galData.Cic * cos(2*ArgLat)); //inclination correction
FP64 u = ArgLat + Su; //corrected arg latitude
FP64 r = smaxis * (1 - (GALChannel[chan].L1galData.e * cos(E))) + Sr; //corrected radius
FP64 i = GALChannel[chan].L1galData.i0 + Si + (GALChannel[chan].L1galData.dot_i * Tk); //corrected inclination
FP64 x1 = r * cos(u);
FP64 y1 = r * sin(u);
x = (x1 * cos(Omega)) - (y1 * cos(i) * sin(Omega));
y = (x1 * sin(Omega)) - (y1 * cos(i) * cos(Omega));
z = y1 * sin(i);
return true;
}

Line-Circle Algorithm not quite working as expected

First, see:
https://math.stackexchange.com/questions/105180/positioning-a-widget-involving-intersection-of-line-and-a-circle
I have an algorithm that solves for the height of an object given a circle and an offset.
It sort of works but the height is always off:
Here is the formula:
and here is a sketch of what it is supposed to do:
And here is sample output from the application:
In the formula, offset = 10 and widthRatio is 3. This is why it is (1 / 10) because (3 * 3) + 1 = 10.
The problem, as you can see is the height of the blue rectangle is not correct. I set the bottom left offsets to be the desired offset (in this case 10) so you can see the bottom left corner is correct. The top right corner is wrong because from the top right corner, I should only have to go 10 pixels until I touch the circle.
The code I use to set the size and location is:
void DataWidgetsHandler::resize( int w, int h )
{
int tabSz = getProportions()->getTableSize() * getProportions()->getScale();
int r = tabSz / 2;
agui::Point tabCenter = agui::Point(
w * getProportions()->getTableOffset().getX(),
h * getProportions()->getTableOffset().getY());
float widthRatio = 3.0f;
int offset = 10;
int height = solveHeight(offset,widthRatio,tabCenter.getX(),tabCenter.getY(),r);
int width = height * widthRatio;
int borderMargin = height;
m_frame->setLocation(offset,
h - height - offset);
m_frame->setSize(width,height);
m_borderLayout->setBorderMargins(0,0,borderMargin,borderMargin);
}
I can assert that the table radius and table center location are correct.
This is my implementation of the formula:
int DataWidgetsHandler::solveHeight( int offset, float widthRatio, float h, float k, float r ) const
{
float denom = (widthRatio * widthRatio) + 1.0f;
float rSq = denom * r * r;
float eq = widthRatio * offset - offset - offset + h - (widthRatio * k);
eq *= eq;
return (1.0f / denom) *
((widthRatio * h) + k - offset - (widthRatio * (offset + offset)) - sqrt(rSq - eq) );
}
It uses the quadratic formula to find what the height should be so that the distance between the top right of the rectangle, bottom left, amd top left are = offset.
Is there something wrong with the formula or implementation? The problem is the height is never long enough.
Thanks
Well, here's my solution, which looks to resemble your solveHeight function. There might be some arithmetic errors in the below, but the method is sound.
You can think in terms of matching the coordinates at the point of the circle across
from the rectangle (P).
Let o_x,o_y be the lower left corner offset distances, w and h be the
height of the rectangle, w_r be the width ratio, dx be the desired
distance between the top right hand corner of the rectangle and the
circle (moving horizontally), c_x and c_y the coordinates of the
circle's centre, theta the angle, and r the circle radius.
Labelling it is half the work! Simply write down the coordinates of the point P:
P_x = o_x + w + dx = c_x + r cos(theta)
P_y = o_y + h = c_y + r sin(theta)
and we know w = w_r * h.
To simplify the arithmetic, let's collect some of the constant terms, and let X = o_x + dx - c_x and Y = o_y - c_y. Then we have
X + w_r * h = r cos(theta)
Y + h = r sin(theta)
Squaring and summing gives a quadratic in h:
(w_r^2 + 1) * h^2 + 2 (X*w_r + Y) h + (X^2+Y^2-r^2) == 0
If you compare this with your effective quadratic, then as long as we made different mistakes :-), you might be able to figure out what's going on.
To be explicit: we can solve this using the quadratic formula, setting
a = (w_r^2 + 1)
b = 2 (X*w_r + Y)
c = (X^2+Y^2-r^2)