Reputation: 45
I am following the tutorial on the following site:
http://harismoonamkunnu.blogspot.co.uk/2013/06/opencv-find-biggest-contour-using-c.html
If I follow the code, it works perfectly. However, what I did is I input a greyscaled image (greyscaled by photoshop and saved as jpg) and I try to skip the step:
cvtColor(src,thr,CV_BGR2GRAY); //Convert to gray
when I run the same code in Visual Studio again, I received a runtime error showing:
Unhandled exception at 0x00007FFE56A79E08 in image_capture.exe: Microsoft C++ exception: cv::Exception at memory location 0x000000C1D58FE1F0. occurred
at countours.cpp file :
scanner = cvStartFindContours( img, storage, cntHeaderSize, mode, method, offset );
I want to try to avoid using the cvtColor because in my application, my input image is a grayscaled picture. My code is as following:
#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);
}
Any idea how to avoid cvtColor()?
Thank you
Upvotes: 3
Views: 5046
Reputation: 1881
According to opencv documentation, input image to findContour
function must be an 8-bit single channel so you must change your input image to that type by threshold
, cvtColor
, etc. And if your image is an gray image, simply load it in CV_LOAD_IMAGE_GRAYSCALE
mode.
cv::Mat rawImg = imread(imgName, CV_LOAD_IMAGE_GRAYSCALE);
Upvotes: 1