OpenCV "findContours"方法错误

OpenCV "findContours" method errors

本文关键字:错误 方法 findContours OpenCV      更新时间:2023-10-16

我在使用OpenCV 2.4.8的"findContours"方法时遇到了问题。具体如下错误:

OpenCV Error: Unsupported format or combination of formats ([Start]FindContours support only 8uC1 and 32sC1 images) in cvStartFindContours, file ........opencvmodulesimgprocsrccontours.cpp, line 196

从消息的内容来看,我似乎使用了不适当的图像格式,但是我很确定我的代码指定了一个 8uC1(8 位 1 通道)矩阵。

/* Threshold source image (src1 which is a grayscale image) */
Mat threshImg(src1.rows, src1.cols, CV_8UC1);
threshold(src1, threshImg, thresh, 255, CV_THRESH_BINARY);
/* Get contours */
Mat threshCopy = threshImg; // Copying image because findContours method edits image data
std::vector<std::vector<Point>> contours;
findContours(threshCopy, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0,0));

我正在使用cl和链接在命令行上编译代码,如下所示:

$: cl NameOfCode.cpp -W2 -EHsc -c -I OpenCVIncludeDirectory
$: link NameOfCode.obj -LIBPATH:OpenCVLibraryDirectory opencv_core248.lib opencv_highgui248.lib opencv_imgproc248.lib

为了启用 cl 和链接的使用,我从 Visual studio 2010 运行 vsvars32.bat:

$: "C:Program FilesMicrosoft Visual Studio 10.0Common7Toolsvsvars32.bat"

我正在重写你的代码,我认为你可以试试。

//Copy the src1 image to threshImg
Mat threshImg = src1.clone(); 
//Covert the threshImg from 8-channel to 1-channel and threshold it to binary image.
cvtColor(threshImg,threshImg, CV_RGB2GRAY); 
threshold(src1, threshImg, thresh, 255, CV_THRESH_BINARY);
//Finnaly you can get a contours.
Mat threshCopy = threshImg.clone;
std::vector<std::vector<Point>> contours;
findContours(threshCopy, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0,0));

看起来问题最终与Visual Studio有关。安装 SP1 后 http://www.microsoft.com/en-us/download/details.aspx?id=23691 并按照 berak 和 vasan 的建议对代码进行调整。最终代码如下:

/* NOTE: Using namespace cv & std */
/* Get input image */
Mat origImg = imread("C:\PathToImage\Image.png", CV_LOAD_IMAGE_GRAYSCALE);
/* Threshold input image */
Mat threshImg;
threshold(origImg, threshImg, 150, 255.0, THRESH_BINARY);
/* Get contours from threshold image */
Mat copyImage = threshImg.clone();
vector<vector<Point>> contours;
findContours(copyImage, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0,0));