[转]opencv+python对图像中对象的中点进行检测


#
-*- coding: utf-8 -*- """ Created on Thu Nov 30 12:11:24 2017 @author: zzz """ #import necessary packages import imutils import cv2 #load the image,convert it to grayscale,blur it slightly # and threshold it image = cv2.imread('shapes_and_colors.png') gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)#grayscale conversion blurred = cv2.GaussianBlur(gray, (5, 5), 0)#Gaussian smoothing using a 5 x 5 kernel thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]#thresholding #find contours in the thresholded image cnts = cv2.findContours(thresh.copy(),cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) #return the set of outlines cnts = cnts[0] if imutils.is_cv2() else cnts[1] #grap appropriate tuple value #loop over the contours for c in cnts: #compute the center of the contour M = cv2.moments(c) cX=int(M["m10"]/M["m00"]) cY=int(M["m01"]/M["m00"]) #draw the contour and center of the shape on the image cv2.drawContours(image,[c],-1,(0,255,0),2) cv2.circle(image,(cX,cY),7,(255,255,255),-1) cv2.putText(image,"center",(cX - 20 ,cY - 20), cv2.FONT_HERSHEY_SIMPLEX,0.5,(255,255,255),2) #show the image cv2.imshow("Image",image) k=cv2.waitKey(0) if k == 27: cv2.destroyAllWindows() elif k ==ord('s'): cv2.imwrite('ahh.png',image) cv2.destroyAllWindows()

原文链接:https://www.pyimagesearch.com/2016/02/01/opencv-center-of-contour/

给定一张图片,要检测轮廓的中心。

 

首先,要对其进行预处理。包括

grayscale conversion
Gaussian smoothing
thresholding等等。
然后调用函数cv2.findcontours,找到这些图形的轮廓并返回一个轮廓集cnts。
M = cv2.moments(c)
    cX=int(M["m10"]/M["m00"])
    cY=int(M["m01"]/M["m00"])
遍历这些轮廓并计算出他们的中心位置。

然后在原图上面画出轮廓,得到的图是这样的,

 



posted @ 2017-11-30 22:22  EarsonLau  阅读(873)  评论(0)    收藏  举报