Efficient way to combine intersecting bounding rectangles

前端 未结 3 784
旧时难觅i
旧时难觅i 2020-12-02 17:19

I\'m trying to simplify the following image using OpenCV:

\"enter

What we have

3条回答
  •  感动是毒
    2020-12-02 18:02

    UPDATE: I misunderstood the question earlier. We don't want to remove rectangles which are completely inside others. We only want to replace the intersecting rectangles. Therefore for the first case, we have to do nothing.

    New api (2.4.9) supports & and | operators.

    From opencv doc:

    • rect = rect1 & rect2 (rectangle intersection)
    • rect = rect1 | rect2 (minimum area rectangle containing rect2 and rect3 )

    It also supports equality comparision (==)

    • rect == rect1

    So it is now very easy to accomplish the task. For every pair of rectangle rect1 and rect2,

    if((rect1 & rect2) == rect1) ... // rect1 is completely inside rect2; do nothing.
    else if((rect1 & rect2).area() > 0) // they intersect; merge them.
        newrect = rect1 | rect2;
        ... // remove rect1 and rect2 from list and insert newrect.
    

    UPDATE 2: (for translating in java)

    I know java very little. I also never used the java API. I am giving here some psudo-code (which I think can be easily translated)

    For & operator, we need a method which finds the intersect of two rectangles.

    Method: Intersect (Rect A, Rect B)
    left = max(A.x, B.x)
    top  = max(A.y, B.y)
    right = min(A.x + A.width, B.x + B.width)
    bottom = min(A.y + A.height, B.y + B.height)
    if(left <= right && top <= bottom) return Rect(left, top, right - left, bottom - top)
    else return Rect()
    

    For | operator, we need a similar method

    Method: Merge (Rect A, Rect B)
    left = min(A.x, B.x)
    top  = min(A.y, B.y)
    right = max(A.x + A.width, B.x + B.width)
    bottom = max(A.y + A.height, B.y + B.height)
    return Rect(left, top, right - left, bottom - top)
    

    For == operator, we can use overloaded equals method.

提交回复
热议问题