Find Circles in an Image using OpenCV in Python
OpenCV平台为python提供了cv2库。这可以用于在计算机视觉中有用的各种形状分析。在本文中,我们将使用Open CV识别圆形。为此,我们将使用cv2.HoughCircles()函数,使用Hough变换在灰度图像中查找圆。在下面的示例中,我们将图像作为输入。然后对其进行复制,并应用此变换功能以识别输出中的圆。
句法
1 2 3 4 5 6 | cv2.HoughCircles(image, method, dp, minDist) Where Image is the image file converted to grey scale Method is the algorithm used to detct the circles. Dp is the inverse ratio of the accumulator resolution to the image resolution. minDist is the Minimum distance between the center coordinates of detected circles. |
例
在下面的示例中,我们使用下面的图像作为输入图像。然后运行以下程序获取圆圈。
下面的程序检测图像文件中是否存在圆圈。如果存在圆圈,则将其突出显示。
例
<!-
现场演示
->
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import cv2 import numpy as np image = cv2.imread('circle_ellipse_2.JPG') output = image.copy() img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Find circles circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1.3, 100) # If some circle is found if circles is not None: # Get the (x, y, r) as integers circles = np.round(circles[0, :]).astype("int") print(circles) # loop over the circles for (x, y, r) in circles: cv2.circle(output, (x, y), r, (0, 255, 0), 2) # show the output image cv2.imshow("circle",output) cv2.waitKey(0) |
运行上面的代码将为我们提供以下结果-
输出量
1 | [[93 98 84]] |
我们得到下图显示的输出。