import cv2
import numpy as np
# 读取图像
img = cv2.capture(0)
# 用来进行轮廓标记的图像
imgContour = img.copy()
kernel = np.ones((5, 5), np.uint8) # 卷积核
font = cv2.FONT_HERSHEY_SIMPLEX # 设置字体样式
# 灰度转换、模糊、边缘提取
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
imgBlur = cv2.GaussianBlur(imgGray, (7, 7), 1)
imgCanny = cv2.Canny(imgBlur, 50, 50)
print(imgCanny.shape)
opening = cv2.morphologyEx(imgGray, cv2.MORPH_OPEN, kernel) # 形态学开运算
bila = cv2.bilateralFilter(imgGray, 10, 200, 200) # 双边滤波消除噪声
# 轮廓提取
contours, hierarchy = cv2.findContours(imgCanny, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
# 对提取的各个轮廓进行遍历
for cnt in contours:
# 计算各个轮廓包围的面积
# area = cv2.contourArea(cnt)
# print(area)
# 将光滑的轮廓线折线化
peri = cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, 0.02 * peri, True)
x, y, w, h = cv2.boundingRect(approx)
cv2.rectangle(imgContour, (x, y), (x + w, y + h), (0, 0, 255), 1)
#根据近似折线段的数目判断目标的形状
objCor = len(approx)
#四条线段时,根据目标包围矩形的宽高比判断是 长方形还是正方形
if objCor == 4 :
#aspRatio = w / float(h)
#if aspRatio > 0.98 and aspRatio < 1.03:
objectType = "s1"
else:
objectType = "s"
# 四条以上线段时为圆形
if objCor > 4:
objectType = " r"
else:
objectType = " "
#
# # 将判断的形状标注在图像上
cv2.putText(imgContour, objectType,
(x + (w // 2) - 10, y + (h // 2) - 10), cv2.FONT_HERSHEY_COMPLEX, 0.1,
(0, 0, 0), 2)
# 识别圆形
circles = cv2.HoughCircles(imgCanny, cv2.HOUGH_GRADIENT, 1, 10, param1=200, param2=15, minRadius=2, maxRadius=12)
if circles is not None: # 如果识别出圆
for circle in circles[0]:
# 获取圆的坐标与半径
x = int(circle[0])
y = int(circle[1])
r = int(circle[2])
cv2.circle(img, (x, y), r, (0, 255, 0), 2) # 标记圆
cv2.circle(img, (x, y), 3, (255, 0, 0), -1) # 标记圆心
#text = 'x: ' + str(x) + ' y: ' + str(y)
cv2.putText(img,"1",(x, y), font, 1, (0, 255, 0), 2, cv2.LINE_AA, 0) # 显示圆心位置
print([x,y])
else:
# 如果识别不出,显示圆心不存在
cv2.putText(img, 'x: No y: No', (10, 30), font, 1, (0, 255, 0), 2, cv2.LINE_AA, 0)
cv2.imshow("img", img)
#cv2.imshow("edge", imgCanny)
cv2.imshow("shape", imgContour)
cv2.waitKey(0)
python Opencv识别圆形并返回坐标
最新推荐文章于 2025-03-23 22:09:41 发布