Home > front end >  How to determine between inner and outer contour with Python OpenCV?
How to determine between inner and outer contour with Python OpenCV?

Time:05-02

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

CodePudding user response:

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 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()
  • Related