在阈值处理之前Opencv中的圆形感兴趣区域

My *_*adr 3 opencv image-processing

我正试图在我的图像中间检测到一个圆形物体.这是一个示例图像:

左半部分是灰度和高斯模糊输入图像; 在Otsu阈值处理后,右半部分是相同的图像.左下角的微小银色阴影导致Otsu门槛误入歧途.有没有办法设置一个感兴趣的圆形区域,以避免角落噪音?

kar*_*lip 5

即使检测到的圆圈有点偏移,也可以直接在一个好的阈值图像上使用霍夫圆变换,适应这种特殊情况:

cv::Mat thres;
cv::threshold(gray, thres, 110, 255, cv::THRESH_BINARY);

std::vector<cv::Vec3f> circles;
cv::HoughCircles(thres, circles, cv::HOUGH_GRADIENT, 1, thres.rows/2, 20, 15);
for (size_t i = 0; i < circles.size(); i++)
{
    cv::Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
    int radius = cvRound(circles[i][2]);
    cv::circle(input, center, 3, cv::Scalar(0, 255, 255), -1);
    cv::circle(input, center, radius, cv::Scalar(0, 0, 255), 1);
}
Run Code Online (Sandbox Code Playgroud)

在更复杂的情况下,您可能必须尝试其他阈值方法,以及填充段的内部零件 (孔)以将它们重建为椭圆形.

下面说明的处理流程执行以下操作以改进硬币的检测:

  • 将输入图像转换为灰度;
  • 适用门槛;
  • 执行形态学操作以连接附近的段;
  • 填充段内的孔;
  • 最后,调用cv::HoughCircles()检测圆形.

通过这种方法可以注意到硬币检测更加集中.无论如何,这是魔术的C++示例代码:

// Load input image
cv::Mat input = cv::imread("coin.jpg");
if (input.empty())
{
    std::cout << "!!! Failed to open image" << std::endl;
    return -1;
}

// Convert it to grayscale
cv::Mat gray;
cv::cvtColor(input, gray, cv::COLOR_BGR2GRAY);

// Threshold the grayscale image for segmentation purposes
cv::Mat thres;
cv::threshold(gray, thres, 110, 255, cv::THRESH_BINARY);
//cv::imwrite("threhsold.jpg", thres);

// Dirty trick to join nearby segments
cv::Mat element = cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(15, 15));
cv::morphologyEx(thres, thres, cv::MORPH_OPEN, element);
//cv::imwrite("morph.jpg", thres);

// Fill the holes inside the segments
fillHoles(thres);
//cv::imwrite("filled.jpg", thres);

// Apply the Hough Circle Transform to detect circles
std::vector<cv::Vec3f> circles;
cv::HoughCircles(thres, circles, cv::HOUGH_GRADIENT, 1, thres.rows/2, 20, 15);
std::cout << "* Number of detected circles: " << circles.size() << std::endl;

for (size_t i = 0; i < circles.size(); i++)
{
    cv::Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
    int radius = cvRound(circles[i][2]);
    cv::circle(input, center, 3, cv::Scalar(0,255,255), -1);
    cv::circle(input, center, radius, cv::Scalar(0,0,255), 1);
}

cv::imshow("Output", input);
//cv::imwrite("output.jpg", input);

cv::waitKey(0);
Run Code Online (Sandbox Code Playgroud)

辅助功能:

void fillHoles(cv::Mat& img)
{
    if (img.channels() > 1)
    {
        std::cout << "fillHoles !!! Image must be single channel" << std::endl;
        return;
    }

    cv::Mat holes = img.clone();
    cv::floodFill(holes, cv::Point2i(0,0), cv::Scalar(1));

    for (int i = 0; i < (img.rows * img.cols); i++)
        if (holes.data[i] == 255)
            img.data[i] = 0;
}
Run Code Online (Sandbox Code Playgroud)