我试过 findContours 有 2 张图片。实际上,它们是一体的。一个是彩色图像(jpg),另一个是由 MS Paint 从颜色创建的(导出为单色图像 - bmp):
#include "cv.h"
#include "highgui.h"
#include "iostream"
using namespace cv;
using namespace std;
char* org_file = "expmap_1.bmp"; //"expmap.jpg"; // "pic1.png";
int main( int argc, char** argv )
{
Mat src;
// the first command line parameter must be file name of binary
// (black-n-white) image
src = imread(org_file, 0); // both are read in binary form
Mat dst = Mat::zeros(src.rows, src.cols, CV_8UC3);
// src = src > 1;
namedWindow( "Source", 1 );
imshow( "Source", src );
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours( src, contours, hierarchy,
CV_RETR_LIST , CV_CHAIN_APPROX_SIMPLE );
// iterate through all the top-level contours,
// draw each connected component with its own random color
cout << contours.size() << endl;
int idx = 0;
for( ; idx >= 0; idx = hierarchy[idx][0] )
{
// Scalar color( rand()&255, rand()&255, rand()&255 );
//Scalar color(255,255,255);
drawContours( dst, contours, idx, RGB(0,0,255), 1, 8, hierarchy );
}
namedWindow( "Components", 1 );
imshow( "Components", dst );
waitKey(0);
最佳答案
请参阅文档 here ,它清楚地表示“在二进制图像中查找轮廓”,这是由于实现的算法的工作方式所致。并注意输入图像应该是“8 位单 channel 图像”。
编辑 : imread(,flags=0) 返回灰度图像,像素未二值化。一种方法是使用 threshold功能。然后结果图像可用于 findContours()。让我知道事情的后续。
编辑 2 : 见 imread在文档中。清楚地说明了标志“= 0 返回灰度图像”,这不是二值化图像!因此,文档中没有错误。
编辑 3 : findContours 确实做了阈值处理,但是阈值是 0。如果你想要一个更高的阈值,你必须首先以更高的阈值对图像进行二值化,然后将结果图像传递给 findContours。您所做的 MS 绘画是以更高的阈值对图像进行二值化。我知道如果您不了解算法的细节,这可能会非常令人困惑。 OpenCV 文档并没有深入解释所有内容,理解所有这些算法的工作原理需要一本厚厚的书。我不是为 OpenCV 文档辩护,这与我无关,但我仍然认为解释中没有错误。不过,新手用户可能会从更深入地讨论算法的工作原理中受益。
关于opencv - findContours 为 "same"图像提供了不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9666846/