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 do after searching for Contours is that you check to see if the area of ββeach contour is less than a given value (I gave 10000, just an assumption), if not more than a contour, avoid it. If the value is less than the specified, it can be our square or the rectangle next to it.
So, we find its width and height and check whether the aspect ratio is close to 1. If so, this 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:

source share