single_blob.py 901 B

12345678910111213141516171819202122232425262728293031323334
  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 image to grayscale image
  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. # calculate moments of binary image
  16. M = cv2.moments(thresh)
  17. # calculate x,y coordinate of center
  18. cX = int(M["m10"] / M["m00"])
  19. cY = int(M["m01"] / M["m00"])
  20. # put text and highlight the center
  21. cv2.circle(img, (cX, cY), 5, (255, 255, 255), -1)
  22. cv2.putText(img, "centroid", (cX - 25, cY - 25),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
  23. # display the image
  24. cv2.imshow("Image", img)
  25. cv2.waitKey(0)