如何基于OpenCV&Python实现霍夫变换圆形检测

  

下面是基于OpenCV&Python实现霍夫变换圆形检测的完整攻略:

1. 什么是霍夫变换

霍夫变换(Hough Transform)是一种图像处理算法,其功能是能够从边缘检测结果中得到直线或圆的方程表达式,即通过边缘点构造直线或圆,并统计在不同参数下断言通过该参数的点的数量,从而得到边缘的位置. 针对圆形检测,霍夫变换算法可以方便地实现圆心的检测。

2. 利用OpenCV实现霍夫圆形检测

2.1 程序示例1

下面是一个简单的程序示例,使用了OpenCV库函数来检测圆形。

import cv2

# load the image and convert it to grayscale
image = cv2.imread('image.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# define the range of radii to be detected
min_radius = 10
max_radius = 30

# apply the HoughCircles function to detect circles
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1.2, 100)

# ensure at least some circles were found
if circles is not None:
    # convert the (x, y) coordinates and radius of the circles to integers
    circles = np.round(circles[0, :]).astype("int")

    # loop over the (x, y) coordinates and radius of the circles
    for (x, y, r) in circles:
        # draw the circle in the output image and update the list of markers
        cv2.circle(image, (x, y), r, (0, 255, 0), 2)

    # show the output image
    cv2.imshow("output", image)
    cv2.waitKey(0)

在上面的程序中,cv2.HoughCircles函数可以直接进行圆形检测。其中,gray是输入图像的灰度图像,cv2.HOUGH_GRADIENT是圆形检测方法,1.2是圆形中心之间的最小距离,100是Canny边缘检测器的上阈值。

2.2 程序示例2

下面是一个更加详细的程序示例,使用了手动实现霍夫圆形检测算法。

import cv2
import numpy as np

# load the image and convert it to grayscale
image = cv2.imread('image.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# apply edge detection (using Canny algorithm)
edges = cv2.Canny(gray, 50, 150)

# initialize accumulator (for the Hough transform)
accumulator = np.zeros((gray.shape[0], gray.shape[1], 30))

# loop through all edge pixels
for y in range(edges.shape[0]):
    for x in range(edges.shape[1]):
        if edges[y, x] == 255:  # if edge pixel
            # loop through a range of radii
            for r in range(10, 40):
                # for each radius, compute the center (x_,y_) of the circle
                for i in range(0, 360):
                    a = x - r * np.cos(i * np.pi / 180)
                    b = y - r * np.sin(i * np.pi / 180)
                    if a >= 0 and a < gray.shape[1] and b >= 0 and b < gray.shape[0]:
                        accumulator[int(b), int(a), r - 10] += 1

# get the (x,y,r) of the center and radius of each detected circle
circles = []
for y in range(gray.shape[0]):
    for x in range(gray.shape[1]):
        for r in range(0, 30):
            if accumulator[y, x, r] > 70:  # if enough edge support
                # add it to the list of detected circles
                circles.append((x, y, r + 10))

# loop through all detected circles and draw them on the output image
for (x, y, r) in circles:
    cv2.circle(image, (x, y), r, (0, 255, 0), 2)

# show the output image
cv2.imshow("output", image)
cv2.waitKey(0)

在上面的程序中,利用Canny算法对灰度图像进行了边缘检测。然后,程序自己实现了霍夫圆形检测算法,可以通过设定r的范围和阈值进行调整。最后,程序解析出检测到的圆的位置和半径,并在原图上画出圆。

相关文章