# Posted By

michaelhecht on 02/06/16

# Statistics

Viewed 517 times
Favorited by 0 user(s)

# detect and measure nested objects with opencv (public)

/ Published in: Python
`import cv2import numpy as np #===================================================================def getObjects(contours,hierarchy):   objs = [] # wichtig wg. Reihenfolge beim plotten  keys = {}   for i in xrange(len(contours)):    h = hierarchy[0][i][3]    a = cv2.contourArea(contours[i])     if h==-1:       keys[i] = len(objs)      objs.append({'out':contours[i],'in':None,'area':a,'id':i})    else:          if keys.has_key(h):         k = keys[h]        objs[k]['in']    = contours[i]        objs[k]['area'] -= a      else:        keys[i] = len(objs)              objs.append({'out':contours[i],'in':None,'area':a,'id':i})   return objs #===================================================================def drawObjects(img,objs,color):   themask  = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)*0   for o in objs:    cv2.drawContours(themask, [o['out']], -1, 255, -1,lineType=cv2.CV_AA)    if o.has_key('in'):       cv2.drawContours(themask, [o['in']], -1,  0, -1,lineType=cv2.CV_AA)   colored = img.copy()  cv2.rectangle(colored,(0,0),(colored.shape[1],colored.shape[0]),color,-1)    colored = cv2.bitwise_and(colored,colored,mask = themask)   img_masked = cv2.add(img,colored)   return img_masked   #=================================================================== img = cv2.imread('3circ.jpg') gray = 255-cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret,thresh = cv2.threshold(gray,127,255,cv2.THRESH_BINARY) contours,hierarchy = cv2.findContours(thresh,cv2.RETR_TREE, cv2.CHAIN_APPROX_TC89_KCOS)for i in xrange(len(hierarchy[0])):  print i,":",hierarchy[0][i] objs = getObjects(contours,hierarchy)img1 = img.copy()for o in objs:   img1 = drawObjects(img1,[o],(0,200,0))  x,y,w,h = cv2.boundingRect(o['out'])  text = "A[%i]=%.0f" % (o['id'],o['area'])  cv2.putText(img1,text,(x,y),cv2.FONT_HERSHEY_SIMPLEX,1,(200,0,200),2,lineType=cv2.CV_AA) all = np.concatenate((img,img1), axis=0)   cv2.imshow('result',all)cv2.imwrite("3circmasked.jpg",all)cv2.waitKey(0)cv2.destroyAllWindows()`