How to know if a bounding box(rectangle) lies inside another bounding box(rectangle)?

Viewed 7478

I am trying to get the boxes(co-ordinates) inside the outer box. I have done using the intersection over union method and I want other methods to do so.enter image description here

Also, can you please tell me how to compare those two inner boxes?

2 Answers

By comparing the coordinates of the top-left and bottom-right corners of the bounding box and the inner boxes it is easy to know if any of the latter is inside the former.

The following code is a simple example with only one bounding box and one inner box:

# Bounding box
boundb = {
    'x': 150,
    'y': 150,
    'height': 50,
    'width': 100
}

# Inner box
innerb = {
    'x': 160,
    'y': 160,
    'height': 25,
    'width': 25
}

# If top-left inner box corner is inside the bounding box
if boundb['x'] < innerb['x'] and boundb['y'] < innerb['y']:
    # If bottom-right inner box corner is inside the bounding box
    if innerb['x'] + innerb['width'] < boundb['x'] + boundb['width'] \
            and innerb['y'] + innerb['height'] < boundb['y'] + boundb['height']:
        print('The entire box is inside the bounding box.')
    else:
        print('Some part of the box is outside the bounding box.')

You may use contours hierarchy.

In the image you have posted, the inner rectangles are contours that has a parent and a child (when using findContours with RETR_TREE flag).

Here is a code sample:

import cv2

# Read input image
img = cv2.imread("boxes.png")

# Convert to gray
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Apply threshold
_, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

# Find contours and hierarchy
cnts, hier = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[-2:]  # Use [-2:] for OpenCV 3, 4 compatibility.

# Draw all contours with green color for testing
cv2.drawContours(img, cnts, -1, (0, 255, 0))

# Hierarchy Representation in OpenCV
# So each contour has its own information regarding what hierarchy it is, 
# who is its child, who is its parent etc. 
# OpenCV represents it as an array of four values : [Next, Previous, First_Child, Parent]

# Iterate contours and hierarchy:
for c, h in zip(cnts, hier[0]):
    # Check if contour has one partent and one at least on child:
    if (h[3] > 0) and (h[2] > 0):
        # Get bounding rectange
        x, y, w, h = cv2.boundingRect(c)

        # Draw red rectange for testing
        cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), thickness=1)


# Show result for testing
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Result:
enter image description here


Update:

I am having a bug in the above code (using > 0 instead of >= 0).
We also need to verify the the parent has a parent.
Looks like it's a bit of an overkill...

# Iterate contours and hierarchy:
for c, h in zip(cnts, hier[0]):
    # Check if contour has one partent and one at least on child:
    if (h[3] >= 0) and (h[2] >= 0):
        # Get the partent from the hierarchy
        hp = hier[0][h[3]]

        # Check if the parent has a parent:
        if hp[3] >= 0:
            # Get bounding rectange
            x, y, w, h = cv2.boundingRect(c)

            # Draw red rectange for testing
            cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), thickness=1)
Related