HoughCircles无法检测此图片上的圆圈

时间:2016-06-27 07:34:30

标签: c++ opencv

我正在尝试检测包含圆点的图像中的圆圈,但不幸的是我无法这样做。我正在使用opencv HoughTransform,但我找不到能够使其工作的参数。

src = imread("encoded.jpg",1);
    /// Convert it to gray
    cvtColor(src, src_gray, CV_BGR2GRAY);

    vector<Vec3f> circles;

    /// Apply the Hough Transform to find the circles
    HoughCircles(src_gray, circles, CV_HOUGH_GRADIENT, 1, 10,
        100, 30, 1, 30 // change the last two parameters
        // (min_radius & max_radius) to detect larger circles
        );

    /// Draw the circles detected
    for (size_t i = 0; i < circles.size(); i++)
    {
        cout << "Positive" << endl;
        Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
        int radius = cvRound(circles[i][2]);
        // circle center
        circle(src, center, 3, Scalar(0, 255, 0), -1, 8, 0);
        // circle outline
        circle(src, center, radius, Scalar(0, 0, 255), 3, 8, 0);
    }

    /// Show your results
    namedWindow("Hough Circle Transform Demo", CV_WINDOW_AUTOSIZE);
    imshow("Hough Circle Transform Demo", src_gray);
    waitKey(0);

我的图片在这里: Input Image

为什么HoughCircles无法检测此图像中的圆圈?它似乎正在处理其他更简单的图像,如电路板。

1 个答案:

答案 0 :(得分:2)

我遇到了您的确切问题并找到了解决方案

关键在于对HoughCircles正在做什么有足够的直觉,这样你就可以构建一个程序来自动调整你想要找到圆圈的所有各种图像的超参数。

核心问题,一些直觉

HoughCircles不会独立存在,即使它表明它可能具有最小和最大半径参数,您需要运行数百或数千次迭代来自动调整并在正确的设置中自动拨号。完成后,您需要后处理验证步骤,以100%确定圆圈是您想要的。问题是你试图通过使用猜测和检查自己手动调整输入参数到HoughCircles。这根本不起作用。让计算机为您自动调整这些参数。

HoughCircles什么时候可以手动调整?

如果你想手工硬编码你的参数,你绝对需要的一件事是圆圈的精确半径在一到两个像素内。您可以猜测dp分辨率并设置累加器阵列投票阈值,您可能没问题。但是如果你不知道半径,那么HoughCircles的输出是无用的,因为无论是在任何地方还是在任何地方都能找到圆圈。并且假设您确实手动找到了可接受的调整,您将其显示为几个像素不同的图像,并且您的HoughCircles会发现并在图像中找到200个圆圈。一文不值。

有希望:

希望来自HoughCircles即使在大型图像上也非常快。您可以为HoughCircles编写程序以完美地自动调整设置。如果你不知道半径,它可能很小或很大,你可以从一个很大的“最小距离参数”,一个非常精细的dp分辨率和一个非常高的投票阈值开始。因此,当您开始迭代并且HoughCircles可预测地拒绝找到任何圈子时,因为设置过于激进并且投票不能清除阈值。但是循环会保持迭代并在最佳设置上爬行,让最佳设置成为发出信号的避雷针。你找到的第一个圆圈将是图像中最完整和最佳圆圈的像素,你会对HoughCircles印象深刻,给你一个像素完美的圆圈,就在它应该的位置。这只是你必须运行它5千次。

示例python代码(抱歉不是C ++):

它的边缘仍然很粗糙,但你应该能够将它清理干净,这样你就可以在一秒钟内获得令人满意的像素。

import numpy as np
import argparse
import cv2
import signal

from functools import wraps
import errno
import os
import copy

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required = True, help = "Path to the image")
args = vars(ap.parse_args())

# load the image, clone it for output, and then convert it to grayscale
image = cv2.imread(args["image"])
orig_image = np.copy(image)
output = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

cv2.imshow("gray", gray)
cv2.waitKey(0)

circles = None

minimum_circle_size = 100      #this is the range of possible circle in pixels you want to find
maximum_circle_size = 150     #maximum possible circle size you're willing to find in pixels

guess_dp = 1.0

number_of_circles_expected = 1          #we expect to find just one circle
breakout = False

#hand tune this
max_guess_accumulator_array_threshold = 100     #minimum of 1, no maximum, (max 300?) the quantity of votes 
                                                #needed to qualify for a circle to be found.
circleLog = []

guess_accumulator_array_threshold = max_guess_accumulator_array_threshold

while guess_accumulator_array_threshold > 1 and breakout == False:
    #start out with smallest resolution possible, to find the most precise circle, then creep bigger if none found
    guess_dp = 1.0
    print("resetting guess_dp:" + str(guess_dp))
    while guess_dp < 9 and breakout == False:
        guess_radius = maximum_circle_size
        print("setting guess_radius: " + str(guess_radius))
        print(circles is None)
        while True:

            #HoughCircles algorithm isn't strong enough to stand on its own if you don't
            #know EXACTLY what radius the circle in the image is, (accurate to within 3 pixels) 
            #If you don't know radius, you need lots of guess and check and lots of post-processing 
            #verification.  Luckily HoughCircles is pretty quick so we can brute force.

            print("guessing radius: " + str(guess_radius) + 
                    " and dp: " + str(guess_dp) + " vote threshold: " + 
                    str(guess_accumulator_array_threshold))

            circles = cv2.HoughCircles(gray, 
                cv2.cv.CV_HOUGH_GRADIENT, 
                dp=guess_dp,               #resolution of accumulator array.
                minDist=100,                #number of pixels center of circles should be from each other, hardcode
                param1=50,
                param2=guess_accumulator_array_threshold,
                minRadius=(guess_radius-3),    #HoughCircles will look for circles at minimum this size
                maxRadius=(guess_radius+3)     #HoughCircles will look for circles at maximum this size
                )

            if circles is not None:
                if len(circles[0]) == number_of_circles_expected:
                    print("len of circles: " + str(len(circles)))
                    circleLog.append(copy.copy(circles))
                    print("k1")
                break
                circles = None
            guess_radius -= 5 
            if guess_radius < 40:
                break;

        guess_dp += 1.5

    guess_accumulator_array_threshold -= 2

#Return the circleLog with the highest accumulator threshold

# ensure at least some circles were found
for cir in circleLog:
    # convert the (x, y) coordinates and radius of the circles to integers
    output = np.copy(orig_image)

    if (len(cir) > 1):
        print("FAIL before")
        exit()

    print(cir[0, :])

    cir = np.round(cir[0, :]).astype("int")

    # loop over the (x, y) coordinates and radius of the circles
    if (len(cir) > 1):
        print("FAIL after")
        exit()

    for (x, y, r) in cir:
        # draw the circle in the output image, then draw a rectangle
        # corresponding to the center of the circle
        cv2.circle(output, (x, y), r, (0, 0, 255), 2)
        cv2.rectangle(output, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)

    # show the output image
    cv2.imshow("output", np.hstack([orig_image, output]))
    cv2.waitKey(0)

因此,如果你运行它,它需要5秒钟,但它几乎完美像素(自动调谐器的进一步手动调整使其完美子像素):

以上代码转换为: Original

对此:

HoughCircles

使这项工作的秘诀在于你在开始之前掌握了多少信息。如果您知道半径到20像素的某个容差,那么这就完美了。但如果你不这样做,你必须明智地了解如何通过仔细接近分辨率和投票门槛来提升最大投票率。如果圆形形状奇怪,则dp分辨率需要更高,并且投票阈值需要探索更低的范围。