Efficient way to combine intersecting bounding rectangles

前端 未结 3 779
旧时难觅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:06

    Given two bounding box contours in the form of (x,y,w,h), here's a function to create a single bounding box (assuming the boxes are touching or within each other). Returns (x,y,w,h) of the combined bounding box i.e, top-left x, top-left y, width, and height. Here's an illustration

    (x1,y1)       w1                           (x3,y3)         w3
      ._____________________.                    .____________________________.
      |                     |                    |                            | 
      |                     |  h1                |                            |
      |   (x2,y2)           |                    |                            |
      |     ._______________|_______.      -->   |                            |
      |     |               |       |            |                            |  h3
      ._____|_______________.       |            |                            |
            |                       |  h2        |                            |
            |                       |            |                            |
            |           w2          |            |                            |
            ._______________________.            .____________________________.
    

    Code

    def combineBoundingBox(box1, box2):
        x = min(box1[0], box2[0])
        y = min(box1[1], box2[1])
        w = box2[0] + box2[2] - box1[0]
        h = max(box1[1] + box1[3], box2[1] + box2[3]) - y
        return (x, y, w, h)
    

    Example

    With these two bounding boxes,

    >>> print(box1)
    >>> print(box2)
    (132, 85, 190, 231)
    (264, 80, 121, 230)
    
    >>> new = combineBoundingBox(box1, box2) 
    >>> print(new)
    (132, 80, 253, 236)
    

    Here's the visual result: Before -> After

提交回复
热议问题