为什么openCV中的输入图像findContours()必须转换为灰度?

时间:2017-10-12 02:45:17

标签: c++ opencv opencv3.0

我正在关注以下网站上的教程:

http://harismoonamkunnu.blogspot.co.uk/2013/06/opencv-find-biggest-contour-using-c.html

如果我遵循代码,它就能完美运行。但是,我所做的是输入一个灰度图像(由photoshop进行灰度化并保存为jpg),我尝试跳过这一步:

cvtColor(src,thr,CV_BGR2GRAY); //Convert to gray

当我再次在Visual Studio中运行相同的代码时,我收到运行时错误,显示:

  

image_capture.exe中0x00007FFE56A79E08处的未处理异常:   Microsoft C ++异常:cv ::内存位置的异常   0x000000C1D58FE1F0。发生

在countours.cpp文件中:

scanner = cvStartFindContours( img, storage, cntHeaderSize, mode, method, offset );

我想尽量避免使用cvtColor,因为在我的应用程序中,我的输入图像是一张灰度图片。我的代码如下:

#include "stdafx.h"
#include <iostream>
#include "opencv2\highgui\highgui.hpp"
#include "opencv\cv.h"
#include "opencv2\imgproc\imgproc.hpp"

using namespace cv;
using namespace std;
int main()
{
 int largest_area=0;
 int largest_contour_index=0;
 Rect bounding_rect;

 Mat src = imread("src.jpg"); //Load source image
 Mat thr(src.rows,src.cols,CV_8UC1); 
 Mat dst(src.rows,src.cols,CV_8UC1,Scalar::all(0));
 //cvtColor(src,thr,CV_BGR2GRAY); //Convert to gray
 threshold(src, src,25, 255,THRESH_BINARY); //Threshold the gray

    vector<vector<Point>> contours; // Vector for storing contour
    vector<Vec4i> hierarchy;

    findContours( src, contours, hierarchy,CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE ); // Find the contours in the image

     for( int i = 0; i< contours.size(); i++ ) // iterate through each contour. 
      {
       double a=contourArea( contours[i],false);  //  Find the area of contour
       if(a>largest_area){
       largest_area=a;
       largest_contour_index=i;                //Store the index of largest contour
       bounding_rect=boundingRect(contours[i]); // Find the bounding rectangle for biggest contour
       }

      }

 Scalar color( 255,255,255);
 drawContours( dst, contours,largest_contour_index, color, CV_FILLED, 8, hierarchy ); // Draw the largest contour using previously stored index.
 rectangle(src, bounding_rect,  Scalar(0,255,0),1, 8,0);  
 imshow( "src", src );
 imshow( "largest Contour", dst );
 waitKey(0);
}

任何想法如何避免cvtColor()?

谢谢

1 个答案:

答案 0 :(得分:0)

根据opencv documentation,输入到plugins: [ new webpack.NormalModuleReplacementPlugin(/tran\.json$/, path.resolve(__dirname, srcRoot, 'empty_tran.json')) ] 功能的图片必须是8位单一频道,因此您必须按findContourthreshold将输入图片更改为该类型如果您的图像是灰色图像,只需将其加载到cvtColor模式。

CV_LOAD_IMAGE_GRAYSCALE