3

我正在通过以下方式打印轮廓:

std::vector<std::vector<cv::Point> > contours;
std::vector<cv::Vec4i> hierarchy;
cv::findContours( mask, contours, hierarchy, cv::RETR_CCOMP, cv::CHAIN_APPROX_TC89_KCOS);
for ( size_t i=0; i<contours.size(); ++i )
{
    cv::drawContours( img, contours, i, Scalar(200,0,0), 1, 8, hierarchy, 0, Point() ); 
    cv::Rect brect = cv::boundingRect(contours[i]);
    cv::rectangle(img, brect, Scalar(255,0,0));
}

一旦我有一个二值图像,我想消除较小的轮廓。关于如何做到这一点的任何建议?

我的输入图片:

在此处输入图像描述

我想要达到的目标:

在此处输入图像描述

编辑:

我试图摆脱较小的部分。有什么提示吗?

4

2 回答 2

1

我建立了一个只打印属于较大段的点的函数。它使用pointPolygonTest,这是一个很棒的 OpenCV 函数,可以判断一个点是在给定轮廓的内部、外部还是边界。一探究竟:

// Gets only the biggest segments
Mat Morphology::threshSegments(Mat &src, double threshSize) {
    // FindContours:
    vector<vector<Point> > contours;
    vector<Vec4i> hierarchy;
    Mat srcBuffer, output;
    src.copyTo(srcBuffer);
    findContours(srcBuffer, contours, hierarchy, cv::RETR_CCOMP, cv::CHAIN_APPROX_TC89_KCOS);

    vector<vector<Point> > allSegments;

    // For each segment:
    for (size_t i = 0; i < contours.size(); ++i) {
        cv::drawContours(srcBuffer, contours, i, Scalar(200, 0, 0), 1, 8, hierarchy, 0, Point());
        cv::Rect brect = cv::boundingRect(contours[i]);
        cv::rectangle(srcBuffer, brect, Scalar(255, 0, 0));

        int result;
        vector<Point> segment;
        for (unsigned int row = brect.y; row < brect.y + brect.height; ++row) {
            for (unsigned int col = brect.x; col < brect.x + brect.width; ++col) {
                result = pointPolygonTest(contours[i], Point(col, row), false);
                if (result == 1 || result == 0) {
                    segment.push_back(Point(col, row));
                }
            }
        }
        allSegments.push_back(segment);
    }

    output = Mat::zeros(src.size(), CV_8U);
    int totalSize = output.rows*output.cols;
    for (int segmentCount = 0; segmentCount < allSegments.size(); ++segmentCount) {
        vector<Point> segment = allSegments[segmentCount];
        if(segment.size() > totalSize*threshSize){
            for (int idx = 0; idx < segment.size(); ++idx) {
                output.at<uchar>(segment[idx].y, segment[idx].x) = 255;
            }
        }
    }

    return output;
}
于 2014-09-10T15:55:19.987 回答
0

我建议使用形态开口来去除较小的斑点,然后进行形态孔填充。

于 2013-11-01T17:55:33.097 回答