How to identify contours within another contour? I tried to go through many OpenCV tutorials but I was unable to identify it. Please can some expert person provide simple code to explain it?
This is my input file
This dark part is the contour that I need to identify.
Please be kind enough to share your experience with me.
Here is a simple approach in Python code. (But as I stated in my comment below, It is not an universal answer applicable everywhere, It is just to show finding contour inside a contour can be done. And if your images are different, then you have to come with some different constraints other than i mentioned below
)
What you are doing after finding Contours is that, you check if area of each contour is less than a specified value ( i gave 10000, just a guess), if not it is bigger contour, avoid it. If less than specified value, it may be our square or rectangle next to it.
So we find its width and height and check if aspect ratio close to 1. if so, it is our square.
import cv2
import numpy as np
img = cv2.imread('sofcnt.jpg')
gray = cv2.imread('sofcnt.jpg',0)
ret,thresh = cv2.threshold(gray,127,255,1)
cont,hier = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
for cnt in cont:
approx = cv2.approxPolyDP(cnt,0.02*cv2.arcLength(cnt,True),True)
if cv2.contourArea(cnt) < 10000:
x,y,w,h = cv2.boundingRect(cnt)
if w/float(h) < 2:
cv2.drawContours(img,[cnt],0,255,-1)
cv2.imshow('a',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Result :