c++ - 在 OpenCV 中寻找轮廓?

标签 c++ image image-processing opencv shape

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

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

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

谢谢。

enter image description here

最佳答案

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

#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

关于c++ - 在 OpenCV 中寻找轮廓?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8449378/

相关文章:

c++ - 尝试访问指向 vector 中对象的指针时出现无效访问错误

c++ - CLion 重命名头文件

html - Logo 不适合导航栏

javascript - 使用 Javascript 从数据库中填充图像到 div

python - 使用 OpenCV 检查图像是否全为白色像素

python - 使用python自动进行图像切割

c++ - 函数和结构与类

iphone - 如何在 iPhone 上将一张图像与另一张图像进行比较,看看它们是否有一定比例的相似度?

将图像矩阵大小复制到 OpenCV 中的另一个矩阵

c++ - c++中的异常处理错误