Path: blob/master/CenterofBlob/center_of_multiple_blob.py
3118 views
import cv21import numpy as np2import argparse34# create object to pass argument5arg_parse = argparse.ArgumentParser()6arg_parse.add_argument("-i", "--ipimage", required=True,7help="input image path")8args = vars(arg_parse.parse_args())910# read image through command line11img = cv2.imread(args["ipimage"])12# convert the image to grayscale13gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)14# convert the grayscale image to binary image15ret,thresh = cv2.threshold(gray_image,127,255,0)1617# find contour in the binary image18im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)19for c in contours:20# calculate moments for each contour21M = cv2.moments(c)22cX = int(M["m10"] / M["m00"])23cY = int(M["m01"] / M["m00"])242526# calculate x,y coordinate of center27cv2.circle(img, (cX, cY), 5, (255, 255, 255), -1)28cv2.putText(img, "centroid", (cX - 25, cY - 25),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)29# display the image30cv2.imshow("Image", img)31cv2.waitKey(0)3233# 3.4.1 im2, contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)34# 3.2.0 im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)3536373839