I'm having problems with the calculation of the distance from a point to a line in a two dimensional space. It's something wrong with the math in this code, but i just can't find the problem. Maybe you can help me with this or have some working functions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
double Detection::distance_to_Line(cv::Point line_start, cv::Point line_end, cv::Point point)
{
cv::Point line; //direction of the line
line.x = line_end.x - line_start.x;
line.y = line_end.y - line_start.y;
cv::Point point_to_start; //vector from the point to the start of the line
point_to_start.x = line_start.x - point.x;
point_to_start.y = line_start.y - point.y;
int dot = point_to_start.x * line.x + point_to_start.y * line.y; //dot product of point_to_start * line
cv::Point distance; //shortest distance vector from point to line
distance.x = point_to_start.x - dot * line.x;
distance.y = point_to_start.y - dot * line.y;
double output = sqrt((double)(distance.x * distance.x + distance.y * distance.y));
return output;
}
cv:Point is from the OpenCV library. You can just use a 2d instead and post your code, if you don't have the library.
double distance_to_line( point begin, point end, point x ){
//translate the begin to the origin
end -= begin;
x -= begin;
//¿do you see the triangle?
double area = cross_product(x, end);
return area / norm(end);
}
As a bonus it would tell you if the point is at the right or the left of the line.