import cv2
import numpy as np
planets = cv2.imread(‘5.png’)
灰度处理
gray_img = cv2.cvtColor(planets, cv2.COLOR_BGR2GRAY)
medianBlur 平滑(模糊)处理
img = cv2.medianBlur(gray_img, 5)
灰度图像转彩色图像
cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)
圆检测
circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1, 100, param1=150, param2=30, minRadius=0, maxRadius=0)
转化整数 np.around 返回四舍五入后的值,可指定精度。
circles = np.uint16(np.around(circles))
y=1
for i in circles[0,:]:
# 勾画圆形,planets图像、(i[0],i[1])圆心坐标,i[2]是半径
cv2.circle(planets,(i[0],i[1]),i[2],(0,255,0),1)
# 勾画圆心,圆心实质也是一个半径为2的圆形
cv2.circle(planets,(i[0],i[1]),1,(0,0,255),2)
cv2.line(planets,(0,i[1]),(i[0],i[1]),(0,0,255),1)
cv2.line(planets,(i[0],0),(i[0],i[1]),(0,0,255),1)
font=cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(planets,str(i[0]),(10,i[1]+13), font, 0.5,(0,0,255),1)
cv2.putText(planets,str(i[1]),(i[0]+13,10), font, 0.5,(0,0,255),1)
cv2.putText(planets,str(i[2]),(i[0]+5,i[1]+5), font, 0.5,(0,0,255),1)
显示图像
print('第',y,'个圆心坐标及半径为',i)
y=y+1
cv2.imwrite(“1273.png”, planets)
cv2.imshow(“mypic”, cimg)
cv2.imshow(“HoughCirlces”, planets)
cv2.waitKey(6000)
cv2.destroyAllWindows()