How to determine between inner and outer contour with Python OpenCV?

Issue

I want to have a polygon region of interest and would like to perform an object detection algorithm within this area.

For example, the user gives some points and I want to create a polygon with them in my code (like the red region) and I want to perform my object detection code inside the red region.

The question is how can I search for object within this area and how should I implement the if conditions for defining IN and OUT areas?

Is there any efficient way to implement this in Python?

enter image description here

Solution

From what I understand, you’re trying to differentiate between outer and inner contours. To determine what contours are IN and OUT, you can simply use contour hierarchy to differentiate between the two. Specifically, when using cv2.findContours you can use cv2.RETR_TREE to extract outer or inner contours. See understanding contour hierarchies: how to distinguish between contours for the full explanation. From the full topology map we are given, we can filter out the contours, the idea is that if a parent contour has inner contours, it means that it’s an OUT contour and the child inside is the IN contour. Another case is if a contour has no inner child then we know it is an IN contour.

Here’s an example to demonstrate:

Input image

enter image description here

Result

enter image description here

Code

import cv2

# Load image, grayscale, Otsu's threshold
image = cv2.imread('2.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Filter using contour hierarchy
cnts, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2:]
hierarchy = hierarchy[0]
for component in zip(cnts, hierarchy):
    currentContour = component[0]
    currentHierarchy = component[1]
    x,y,w,h = cv2.boundingRect(currentContour)
    # Has inner contours which means it is IN
    if currentHierarchy[2] < 0:
        cv2.putText(image, 'IN', (x,y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (36,255,12), 2)
    # No child which means it is OUT
    elif currentHierarchy[3] < 0:
        cv2.putText(image, 'OUT', (x,y-5), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (36,255,12), 2)

cv2.imshow('image', image)
cv2.waitKey()

Answered By – nathancy

Answer Checked By – Marie Seifert (AngularFixing Admin)

Leave a Reply

Your email address will not be published.