Advertisement
Guest User

Untitled

a guest
Aug 26th, 2016
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. import cv2
  2.  
  3. lemBGR = cv2.imread("lem.png")
  4. lem = cv2.cvtColor(lemBGR,cv2.COLOR_BGR2GRAY)
  5.  
  6. # Dilate the image in order to close any external contour of the leming
  7. kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
  8. lem = cv2.dilate(lem,kernel)
  9.  
  10. # Identify holes in the leming contour
  11. # This could be done by iterative morphological operations,
  12. # but this is not directly implemented in OpenCV
  13. contour,hier = cv2.findContours(lem.copy(),cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE)
  14. # And fill them
  15. for c,h in zip(contour, hier[0]):
  16. if h[3]!=-1:
  17. cv2.drawContours(lem,[c],0,255,-1)
  18.  
  19. # Now bring the leming back to its original size
  20. lem = cv2.erode(lem,kernel)
  21.  
  22. # Remove the cord by wiping-out all vertical lines
  23. kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(15,1))
  24. #lem = cv2.erode(lem,kernel) # first wipe-out
  25. #lem = cv2.dilate(lem,kernel) # then bring back to original size
  26. # erode and then dilate is the same as opening
  27. lem = cv2.morphologyEx(lem,cv2.MORPH_OPEN,kernel)
  28.  
  29. # Find the contour of the leming
  30. contour,_ = cv2.findContours(lem.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
  31.  
  32. # And draw it on the original image
  33. for c in contour:
  34. # enter your filtering here
  35. x,y,w,h = cv2.boundingRect(c)
  36. cv2.rectangle(lemBGR,(x,y),(x+w,y+h),(0,255,0),2)
  37.  
  38. # Display the result
  39. cv2.imshow("lem",lemBGR)
  40. cv2.waitKey()
  41.  
  42. cv2.imwrite("lem-res.png",lemBGR)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement