问题
I'm writing a function that evaluates how many pixels overlap between two non-isosceles trapezoids. In my application, a trapezoid is always defined as :
typedef std::array<cv::Point, 4> Trapezoid;
//[0] - bottom left
//[1] - bottom right
//[2] - top right
//[3] - top left
Additionally, these trapezoids will have the properties that indexes [0] and [1] will always have the same Y as will [2] and [3] (Always parallel to Y axis).
So, let's say I have two trapezoids:
//300 high, 100 top, 200 bottom
Trapezoid trapezoid1{ cv::Point(100,400), cv::Point(300,400), cv::Point(250,100), cv::Point(150,100) };
//250 high, 50 top, 250 bottom
Trapezoid trapezoid2{ cv::Point(75,400), cv::Point(325,400), cv::Point(225,150), cv::Point(175,150) };
I could iterate over each row of one of the trapezoids and do the math to figure out how many pixels in that row overlap:
uint32_t TrapezoidOverlap( const Trapezoid& trapezoid1,
const Trapezoid& trapezoid2 )
{
//Count number of overlapping pixels
uint32_t overlappedpixels {0};
for (int i = trapezoid1[3].y; i < trapezoid1[0].y; i++) {
overlappedpixels += //Math for overlapping pixels in X;
}
return overlappedpixels;
}
First and last row will be simple, but all rows in between will require trigonometry to find the start and end points of both trapezoids. This looks like it will be computationally expensive and performance is critical in this application. I have seen in this question that the Rect structures have a intersection operator, however I am not sure if there's any function that would help in this situation.
What would be the solution for best performance in this situation?
回答1:
Draw the trapezoids or polygons using CV_FILLED
or fillPoly
in two matrix and AND them logically. Area of intersection is:
int area_int = countNonZero(bitwise_and(TrapeZoidMatA,TrapeZoidMatB));
I think this would be much efficient in this case.
来源:https://stackoverflow.com/questions/40240484/find-intersecting-area-of-two-trapezoids-in-opencv