Sean M.
Sean M.

Reputation: 593

How to connect OpenCV contours horizontally?

I'm using findContours in Opencv 2.9 (C++). What I obtain is a vector> contours, which describes my contours. Lets say I've got a rectangle with its contour stored in the vector. What I would like to do next is, to connect the left and right side of the contour at any point with a line. E.g. 10 pixels below the upper left corner to the 10 pixels below upper right corner of the rectangle. The line should end where the contour does. Is there a better approach then just going scanline wise through that lane and checking every pixel if pointPolygonTest is true?

Thanks in advance!

Upvotes: 0

Views: 874

Answers (1)

OpenMinded
OpenMinded

Reputation: 1175

Suppose you have corners (top-left, top-right, bottom-right and bottom-left points) then you can easily calculate intersections between two lines each defined with two points.

For example, line(P1, P4) intersects with line(R1,R2) and the intersection point is I:

enter image description here

Here is a snippet code for calculating intersection point if the lines do intersect:

// Finds the intersection of two lines, or returns false.
// The lines are defined by (o1, p1) and (o2, p2).
bool intersection(cv::Point2f o1, cv::Point2f p1, cv::Point2f o2, cv::Point2f p2, cv::Point2f &r)
{
    cv::Point2f x = o2 - o1;
    cv::Point2f d1 = p1 - o1;
    cv::Point2f d2 = p2 - o2;

    float cross = d1.x*d2.y - d1.y*d2.x;
    if (std::abs(cross) < /*EPS*/1e-8)
        return false;

    double t1 = (x.x * d2.y - x.y * d2.x)/cross;
    r = o1 + d1 * t1;
    return true;
}

Upvotes: 1

Related Questions