首页 文章

在OpenCV中查找轮廓?

提问于
浏览
14

从图像中检索轮廓时,每个斑点应获得2个轮廓 - 一个内部轮廓和一个外部轮廓 . 考虑下面的圆圈 - 由于圆是像素宽度大于1的线,您应该能够在图像中找到两个轮廓 - 一个来自圆的内部,一个来自外部 .

使用OpenCV,我想检索INNER轮廓 . 但是,当我使用findContours()时,我似乎只是在获得外部轮廓 . 如何使用OpenCV检索blob的内部轮廓?

我使用的是C API,而不是C,因此只建议使用C API的函数 . (即findContours()而不是cvFindContours())

谢谢 .

enter image description here

3 回答

  • 3

    我在你的图像上运行了这个代码,它返回了一个内外轮廓 .

    #include <iostream>
    #include "opencv2/core/core.hpp"
    #include "opencv2/imgproc/imgproc.hpp"
    #include "opencv2/highgui/highgui.hpp"
    
    int main(int argc, const char * argv[]) {
    
        cv::Mat image= cv::imread("../../so8449378.jpg");
        if (!image.data) {
            std::cout << "Image file not found\n";
            return 1;
        }
    
        //Prepare the image for findContours
        cv::cvtColor(image, image, CV_BGR2GRAY);
        cv::threshold(image, image, 128, 255, CV_THRESH_BINARY);
    
        //Find the contours. Use the contourOutput Mat so the original image doesn't get overwritten
        std::vector<std::vector<cv::Point> > contours;
        cv::Mat contourOutput = image.clone();
        cv::findContours( contourOutput, contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE );
    
        //Draw the contours
        cv::Mat contourImage(image.size(), CV_8UC3, cv::Scalar(0,0,0));
        cv::Scalar colors[3];
        colors[0] = cv::Scalar(255, 0, 0);
        colors[1] = cv::Scalar(0, 255, 0);
        colors[2] = cv::Scalar(0, 0, 255);
        for (size_t idx = 0; idx < contours.size(); idx++) {
            cv::drawContours(contourImage, contours, idx, colors[idx % 3]);
        }
    
        cv::imshow("Input Image", image);
        cvMoveWindow("Input Image", 0, 0);
        cv::imshow("Contours", contourImage);
        cvMoveWindow("Contours", 200, 0);
        cv::waitKey(0);
    
        return 0;
    }
    

    以下是它发现的轮廓:

    findContour result image

  • 0

    我认为Farhad要求的是从原始图像中裁剪轮廓 .

    为此,您需要找到如上所述的轮廓,然后使用蒙版从原件获取内部,然后将结果裁剪为与轮廓尺寸相同的图像 .

  • 25

    findcontours函数将所有轮廓存储在不同的向量中,在给出所有轮廓的代码中,您只需绘制对应于内部轮廓的轮廓,idx是指示绘制轮廓的变量 .

相关问题