python Opencv识别圆形并返回坐标

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)

  • 3
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值