Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/learnopencv
Path: blob/master/CenterofBlob/single_blob.py
3118 views
1
import cv2
2
import numpy as np
3
import argparse
4
5
# create object to pass argument
6
arg_parse = argparse.ArgumentParser()
7
arg_parse.add_argument("-i", "--ipimage", required=True,
8
help="input image path")
9
args = vars(arg_parse.parse_args())
10
11
# read image through command line
12
img = cv2.imread(args["ipimage"])
13
14
# convert image to grayscale image
15
gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
16
17
# convert the grayscale image to binary image
18
ret,thresh = cv2.threshold(gray_image,127,255,0)
19
20
# calculate moments of binary image
21
M = cv2.moments(thresh)
22
23
# calculate x,y coordinate of center
24
cX = int(M["m10"] / M["m00"])
25
cY = int(M["m01"] / M["m00"])
26
27
# put text and highlight the center
28
cv2.circle(img, (cX, cY), 5, (255, 255, 255), -1)
29
cv2.putText(img, "centroid", (cX - 25, cY - 25),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
30
31
# display the image
32
cv2.imshow("Image", img)
33
cv2.waitKey(0)
34
35