5

我正在研究 opencv 问题以找出填充了哪些圆圈。然而,有时圆的边缘是误报的原因。我想知道是否可以通过将所有在 RGB 中具有高 R 值的像素变为白色来移除这些圆圈。我的方法是创建一个粉红色的像素蒙版,然后从原始图像中减去蒙版以去除圆圈。截至目前,我正在获得黑色面具。我做错了什么。请指导。

    rgb = cv2.imread(img, cv2.CV_LOAD_IMAGE_COLOR)
    rgb_filtered = cv2.inRange(rgb, (200, 0, 90), (255, 110, 255))
    cv2.imwrite('mask.png',rgb_filtered) 

在此处输入图像描述

4

3 回答 3

5

这是我的解决方案。不幸的是,它也在 C++ 中,这就是它的工作原理:

  1. 阈值图像以找出哪些部分是背景(白皮书)
  2. 通过提取轮廓找到圆圈。
  3. 现在假设每个轮廓都是一个圆,因此计算包围该轮廓的最小圆。如果输入正常,则无需进行参数调整(这意味着每个圆都是单个轮廓,因此例如可能无法通过绘图来连接圆)
  4. 检查每个圆圈,内部是否有更多的前景(绘图)或背景(白皮书)像素(按某个比率阈值)。

    int main()
    {
    cv::Mat colorImage = cv::imread("countFilledCircles.png");
    cv::Mat image = cv::imread("countFilledCircles.png", CV_LOAD_IMAGE_GRAYSCALE);
    
    // threshold the image!
    cv::Mat thresholded;
    cv::threshold(image,thresholded,0,255,CV_THRESH_BINARY_INV | CV_THRESH_OTSU);
    
    // save threshold image for demonstration:
    cv::imwrite("countFilledCircles_threshold.png", thresholded);
    
    
    // find outer-contours in the image these should be the circles!
    cv::Mat conts = thresholded.clone();
    std::vector<std::vector<cv::Point> > contours;
    std::vector<cv::Vec4i> hierarchy;
    
    cv::findContours(conts,contours,hierarchy, CV_RETR_EXTERNAL, CV_C    HAIN_APPROX_SIMPLE, cv::Point(0,0));
    
    
    
    // colors in which marked/unmarked circle outlines will be drawn:
    cv::Scalar colorMarked(0,255,0);
    cv::Scalar colorUnMarked(0,0,255);
    
    // each outer contour is assumed to be a circle
    // TODO: you could first find the mean radius of all assumed circles and try to find outlier (dirt etc in the image)
    for(unsigned int i=0; i<contours.size(); ++i)
    {
            cv::Point2f center;
            float radius;
            // find minimum circle enclosing the contour
            cv::minEnclosingCircle(contours[i],center,radius);
    
            bool marked = false;
    
        cv::Rect circleROI(center.x-radius, center.y-radius, center.x+radius, center.y+radius);
        //circleROI = circleROI & cv::Rect(0,0,image.cols, image.rows);
    
        // count pixel inside the circle
        float sumCirclePixel = 0;
        float sumCirclePixelMarked = 0;
        for(int j=circleROI.y; j<circleROI.y+circleROI.height; ++j)
            for(int i=circleROI.x; i<circleROI.x+circleROI.width; ++i)
            {
                cv::Point2f current(i,j);
                // test if pixel really inside the circle:
            if(cv::norm(current-center) < radius)
                {
                    // count total number of pixel in the circle
                    sumCirclePixel = sumCirclePixel+1.0f;
                    // and count all pixel in the circle which hold the segmentation threshold
                    if(thresholded.at<unsigned char>(j,i))
                        sumCirclePixelMarked = sumCirclePixelMarked + 1.0f;
                }
            }
    
        const float ratioThreshold = 0.5f;
        if(sumCirclePixel)
            if(sumCirclePixelMarked/sumCirclePixel > ratioThreshold) marked = true;
    
        // draw the circle for demonstration
        if(marked)
            cv::circle(colorImage,center,radius,colorMarked,1);
        else
            cv::circle(colorImage,center,radius,colorUnMarked,1);
        }
    
    
    cv::imshow("thres", thresholded);
    cv::imshow("colorImage", colorImage);
    cv::imwrite("countFilledCircles_output.png", colorImage);
    
    cv::waitKey(-1);
    }
    

给我这些结果:

大津阈值处理后:

在此处输入图像描述

最终图像:

在此处输入图像描述

于 2014-04-08T10:54:49.950 回答
1

我试图在 Python 中提出一个解决方案。基本上流程如下:

  • 高斯模糊以减少噪声。
  • 大津的门槛。
  • 找到没有父母的轮廓,那些轮廓应该是圆圈。
  • 检查每个轮廓内的白色与黑色像素的比率。

您可能需要调整白色比率阈值以适合您的应用程序。我使用了 0.7,因为它似乎是一个合理的值。

import cv2
import numpy

# Read image and apply gaussian blur

img = cv2.imread("circles.png", cv2.CV_LOAD_IMAGE_GRAYSCALE)
img = cv2.GaussianBlur(img, (5, 5), 0)

# Apply OTSU thresholding and reverse it so the circles are in the foreground (white)

_, otsu = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
otsu = cv2.bitwise_not(otsu).astype("uint8")

# Find contours that have no parent

contours, hierarchy = cv2.findContours(numpy.copy(otsu), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
parent_contours = [contours[idx] for idx, val in enumerate(hierarchy[0]) if val[3] == -1]

# Loop through all contours to check the ratio of white to black pixels inside each one

filled_circles_contours = list()

for contour in parent_contours:

    contour_mask = numpy.zeros(img.shape).astype("uint8")
    cv2.drawContours(contour_mask, [contour], -1, 1, thickness=-1)
    white_len_mask = len(cv2.findNonZero(contour_mask))
    white_len_thresholded = len(cv2.findNonZero(contour_mask * otsu))
    white_ratio = float(white_len_thresholded) / white_len_mask

    if white_ratio > 0.7:
        filled_circles_contours.append(contour)

# Show image with detected circles

cv2.drawContours(img, filled_circles_contours, -1, (0, 0, 0), thickness=2)
cv2.namedWindow("Result")
cv2.imshow("Result", img)
cv2.waitKey(0)

这是我将上面的代码应用于您的图像所获得的结果:

实心圆检测结果

于 2014-04-08T11:23:42.473 回答
0

我是这样做的:

  1. 转换为灰度,应用高斯模糊去除噪点
  2. 应用 otsu 阈值,分离前背景非常好,你应该阅读它
  3. 应用霍夫圆变换来寻找候选圆,遗憾的是这需要大量调整。也许分水岭分割是一个更好的选择
  4. 从候选圆圈中提取 ROI,并找出黑白像素的比例。

这是我的示例结果: 在此处输入图像描述

当我们在原始图像上绘制结果时: 在此处输入图像描述

这是示例代码(对不起,在 C++ 中):

void findFilledCircles( Mat& img ){
    Mat gray;
    cvtColor( img, gray, CV_BGR2GRAY );

    /* Apply some blurring to remove some noises */
    GaussianBlur( gray, gray, Size(5, 5), 1, 1);

    /* Otsu thresholding maximizes inter class variance, pretty good in separating background from foreground */
    threshold( gray, gray, 0.0, 255.0, CV_THRESH_OTSU );
    erode( gray, gray, Mat(), Point(-1, -1), 1 );

    /* Sadly, this is tuning heavy, adjust the params for Hough Circles */
    double dp       = 1.0;
    double min_dist = 15.0;
    double param1   = 40.0;
    double param2   = 10.0;
    int min_radius  = 15;
    int max_radius  = 22;

    /* Use hough circles to find the circles, maybe we could use watershed for segmentation instead(?) */
    vector<Vec3f> found_circles;
    HoughCircles( gray, found_circles, CV_HOUGH_GRADIENT, dp, min_dist, param1, param2, min_radius, max_radius );

    /* This is just to draw coloured circles on the 'originally' gray image */
    vector<Mat> out = { gray, gray, gray };
    Mat output;
    merge( out, output );

    float diameter  = max_radius * 2;
    float area      = diameter * diameter;

    Mat roi( max_radius, max_radius, CV_8UC3, Scalar(255, 255, 255) );
    for( Vec3f circ: found_circles ) {
    /* Basically we extract the region of the circles, and count the ratio of black pixels (0) and white pixels (255) */
        Mat( gray, Rect( circ[0] - max_radius, circ[1] - max_radius, diameter, diameter ) ).copyTo( roi );
        float filled_percentage = 1.0 - 1.0 * countNonZero( roi ) / area;

        /* If more than half is filled, then maybe it's filled */
        if( filled_percentage > 0.5 )
            circle( output, Point2f( circ[0], circ[1] ), max_radius, Scalar( 0, 0, 255), 3 );
        else
            circle( output, Point2f( circ[0], circ[1] ), max_radius, Scalar( 255, 255, 0), 3 );
    }


    namedWindow("");
    moveWindow("", 0, 0);
    imshow("", output );
    waitKey();
}
于 2014-04-08T09:58:38.050 回答