Slope and Length of a line between 2 points in OpenCV
10,763
Well, this is a math question.
Assume you have two points: p1(x1,y1)
and p2(x2,y2)
. Let's call p1
the "start" and p2
the "end" of the line segment, as you have called the points you have.
slope = (y2 - y1) / (x2 - x1) length = norm(p2 - p1)
Sample code:
cv::Point p1 = cv::Point(5,0); // "start"
cv::Point p2 = cv::Point(10,0); // "end"
// we know this is a horizontal line, then it should have
// slope = 0 and length = 5. Let's see...
// take care with division by zero caused by vertical lines
double slope = (p2.y - p1.y) / (double)(p2.x - p1.x);
// (0 - 0) / (10 - 5) -> 0/5 -> slope = 0 (that's correct, right?)
double length = cv::norm(p2 - p1);
// p_2 - p_1 = (5, 0)
// norm((0,5)) = sqrt(5^2 + 0^2) = sqrt(25) -> length = 5 (that's correct, right?)
Related videos on Youtube
Author by
Aydin
Updated on June 04, 2022Comments
-
Aydin almost 2 years
I need to compare 2 pictures to find similar lines among them. In both pictures I use LSD (Line Segments Detector) method, then I find lines and I know coordinates of start and end points of each line.
My question is: is there any function in OpenCV to find the slope and length of each line, so that I can compare them easily?
My environment is: OpenCV 3.1, C++ and Visual Studio 2015
-
Aydin almost 8 yearsthanks,I know it is math question just I was wondering maybe there is some ready functions.so i will use this code.
-
Berriel almost 8 years@Aydin no problem :) I see myself in this situation many times too
-
Aydin almost 8 yearsthere is some other functions in openCv like magnitude or absdiff, but I don't know how to use it , can you help me?
-
Berriel almost 8 years@Aydin sure.
magnitude
and the Euclidean norm are the same thing. Andabsdiff
is just a saturated absolute difference between two elements. Oh, don't forget to mark as answer if that helped you. If you have any doubts about their use, just ask. -
Berriel almost 8 years@Aydin no problem. Comments are not the appropriate way of doing this. You can get good examples from OpenCV tutorials, but anytime you have a particular problem, just ask a question here on SO. Just remember to follow the community guidelines.