Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/learnopencv
Path: blob/master/CenterofBlob/center_of_multiple_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
# convert the image to grayscale
14
gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
15
# convert the grayscale image to binary image
16
ret,thresh = cv2.threshold(gray_image,127,255,0)
17
18
# find contour in the binary image
19
im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
20
for c in contours:
21
# calculate moments for each contour
22
M = cv2.moments(c)
23
cX = int(M["m10"] / M["m00"])
24
cY = int(M["m01"] / M["m00"])
25
26
27
# calculate x,y coordinate of 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
# display the image
31
cv2.imshow("Image", img)
32
cv2.waitKey(0)
33
34
# 3.4.1 im2, contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
35
# 3.2.0 im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
36
37
38
39