detect and measure nested objects with opencv (public)


/ Published in: Python
Save to your folder(s)

OpenCV object detection


Copy this code and paste it in your HTML
  1. import cv2
  2. import numpy as np
  3.  
  4. #===================================================================
  5. def getObjects(contours,hierarchy):
  6.  
  7. objs = [] # wichtig wg. Reihenfolge beim plotten
  8. keys = {}
  9.  
  10. for i in xrange(len(contours)):
  11. h = hierarchy[0][i][3]
  12. a = cv2.contourArea(contours[i])
  13.  
  14. if h==-1:
  15. keys[i] = len(objs)
  16. objs.append({'out':contours[i],'in':None,'area':a,'id':i})
  17. else:
  18. if keys.has_key(h):
  19. k = keys[h]
  20. objs[k]['in'] = contours[i]
  21. objs[k]['area'] -= a
  22. else:
  23. keys[i] = len(objs)
  24. objs.append({'out':contours[i],'in':None,'area':a,'id':i})
  25.  
  26. return objs
  27.  
  28. #===================================================================
  29. def drawObjects(img,objs,color):
  30.  
  31. themask = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)*0
  32.  
  33. for o in objs:
  34. cv2.drawContours(themask, [o['out']], -1, 255, -1,lineType=cv2.CV_AA)
  35. if o.has_key('in'):
  36. cv2.drawContours(themask, [o['in']], -1, 0, -1,lineType=cv2.CV_AA)
  37.  
  38. colored = img.copy()
  39. cv2.rectangle(colored,(0,0),(colored.shape[1],colored.shape[0]),color,-1)
  40. colored = cv2.bitwise_and(colored,colored,mask = themask)
  41.  
  42. img_masked = cv2.add(img,colored)
  43.  
  44. return img_masked
  45.  
  46. #===================================================================
  47.  
  48. img = cv2.imread('3circ.jpg')
  49.  
  50. gray = 255-cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  51.  
  52. ret,thresh = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
  53.  
  54. contours,hierarchy = cv2.findContours(thresh,cv2.RETR_TREE, cv2.CHAIN_APPROX_TC89_KCOS)
  55. for i in xrange(len(hierarchy[0])):
  56. print i,":",hierarchy[0][i]
  57.  
  58. objs = getObjects(contours,hierarchy)
  59. img1 = img.copy()
  60. for o in objs:
  61. img1 = drawObjects(img1,[o],(0,200,0))
  62. x,y,w,h = cv2.boundingRect(o['out'])
  63. text = "A[%i]=%.0f" % (o['id'],o['area'])
  64. cv2.putText(img1,text,(x,y),cv2.FONT_HERSHEY_SIMPLEX,1,(200,0,200),2,lineType=cv2.CV_AA)
  65.  
  66. all = np.concatenate((img,img1), axis=0)
  67.  
  68. cv2.imshow('result',all)
  69. cv2.imwrite("3circmasked.jpg",all)
  70. cv2.waitKey(0)
  71. cv2.destroyAllWindows()

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.