center_of_multiple_blob.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import cv2
  2. import numpy as np
  3. import argparse
  4. # create object to pass argument
  5. arg_parse = argparse.ArgumentParser()
  6. arg_parse.add_argument("-i", "--ipimage", required=True,
  7. help="input image path")
  8. args = vars(arg_parse.parse_args())
  9. # read image through command line
  10. img = cv2.imread(args["ipimage"])
  11. # convert the image to grayscale
  12. gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  13. # convert the grayscale image to binary image
  14. ret,thresh = cv2.threshold(gray_image,127,255,0)
  15. # find contour in the binary image
  16. im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
  17. for c in contours:
  18. # calculate moments for each contour
  19. M = cv2.moments(c)
  20. cX = int(M["m10"] / M["m00"])
  21. cY = int(M["m01"] / M["m00"])
  22. # calculate x,y coordinate of center
  23. cv2.circle(img, (cX, cY), 5, (255, 255, 255), -1)
  24. cv2.putText(img, "centroid", (cX - 25, cY - 25),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
  25. # display the image
  26. cv2.imshow("Image", img)
  27. cv2.waitKey(0)
  28. # 3.4.1 im2, contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
  29. # 3.2.0 im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)