Ask Your Question

Revision history [back]

i think you need just a simple function like

Rect find_boundingRect( Mat image ) // returns bounding box of non-zero pixels 
{
    Mat Points;
    findNonZero( image, Points );
    Rect _boundingRect = boundingRect( Points );
    return _boundingRect;
}

instead of your void find_contour(Mat image)

you can understand the usage by testing the code below. i tried to explain by comments.

( see also http://answers.opencv.org/question/4183 thanks @Balaji R )

#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"

using namespace cv;

Rect find_boundingRect( Mat image )
{
    Mat Points;
    findNonZero( image, Points );
    Rect _boundingRect = boundingRect( Points );
    return _boundingRect;
}
// adopted from http://answers.opencv.org/question/4183 thanks @Balaji R
int main( int argc, char** argv )
{
    char* filename = argc >= 2 ? argv[1] : (char*)"14521348155732744.jpeg";

    Mat mSource_Bgr,mSource_Gray,mThreshold;
    mSource_Bgr = imread( filename );

    cvtColor( mSource_Bgr, mSource_Gray, COLOR_BGR2GRAY );

    // note #1
    // here i assume you find eye location and do some image processing
    // eyeRect is just to simulate it
    Rect eyeRect( 5, 5, mSource_Bgr.cols - 10, mSource_Bgr.rows -10 );
    Mat mEye = mSource_Gray( eyeRect );

    threshold( mEye, mThreshold, 127, 255, THRESH_BINARY_INV );

    Rect _boundingRect = find_boundingRect( mThreshold );
    _boundingRect.x += eyeRect.x; // see note #1
    _boundingRect.y += eyeRect.y; // see note #1

    rectangle( mSource_Bgr, _boundingRect, Scalar(0,255,0), 2 );

    imshow("Result",mSource_Bgr);
    waitKey(0);

    return 0;
}

image description - image description-image description-image description