python-opencv检测圆

前言

需要用到圆检测,记录一下

代码

# 在一张图片上检测圆
import cv2
import os
import numpy as np


def detect_circle(img):
    """在一张图片上检测圆
    img: 必须是二值化的图
    """
    # img = img * 255
    img_bgr = np.stack([img,img,img],axis=-1)
    img = cv2.medianBlur(img,5)
    # param2越小,检测到的圆越多
    circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,20,
                param1=10,param2=10,minRadius=10,maxRadius=70)
    # print(circles)
    circles = np.uint16(np.around(circles))
    # 因为我这里只检测一个圆,需要检测多个圆的话,就遍历circles
    assert len(circles)==1,f'{circles},not qualify only a circle!'
    (x,y,r) = circles[0][0]
    # input(circles[0,:])
    show = True
    if show==True:
        cv2.circle(img_bgr,(x,y),r,(0,0,255),2)
        # 圆心
        cv2.circle(img_bgr,(x,y),2,(0,255,0),3)
        cv2.imshow('w',img_bgr)
        cv2.waitKey(0)
    # 这里的x对应w,y对应d
    return (x,y,r),img_bgr # 返回横纵坐标和半径、rgb图




if __name__ == '__main__':
    file_path = "../dir_007/pngs/220.png"
    img = cv2.imread(file_path,0)
    # print(np.unique(img))
    detect_circle(img)

结果

python-opencv检测圆_第1张图片

你可能感兴趣的:(图像,opencv,opencv,python,计算机视觉)