Ask Your Question

Revision history [back]

using Morphological Transformations you can find the biggest white area as shown with the code below.

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

using namespace cv;
using namespace std;

int main( int, char** argv )
{
    Mat src,src_gray,eroded;
    src = imread("test_opencv.jpg");
    if (src.empty())
    {
        return -1;
    }

    int scale = 4;
    cvtColor( src, src_gray, COLOR_BGR2GRAY );
    resize(src_gray,src_gray,Size(src_gray.cols/scale,src_gray.rows/scale )); // optionally resize image to speed up the process
    src_gray = src_gray >127;

    vector<vector<Point> > contours;

    for( int i = 2 ; i < src_gray.cols/2   ; i++ )
    {
        cv::Mat kernel = cv::Mat::ones(i, i, CV_8U);
        erode(src_gray,eroded, kernel);

        findContours( eroded, contours, RETR_LIST, CHAIN_APPROX_SIMPLE, Point(0, 0) );
        if( contours.size()== 1 & contours[0].size() < 5 )
        {
            dilate(eroded,eroded, kernel);
            findContours( eroded, contours, RETR_LIST, CHAIN_APPROX_SIMPLE, Point(0, 0) );
            polylines( src, Mat( contours[0] ) * scale, true, Scalar(0,0,255)); // resize up the contour and draw
            break;
        }
    }
    imshow( "result", src );

    waitKey(0);
    return(0);
}

resized result image:

image description

using Morphological Transformations you can find the biggest white area as shown with the code below.

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

using namespace cv;
using namespace std;

int main( int, main(int argc, char** argv )
argv)
{
    Mat src,src_gray,eroded;

    char* filename = argc >= 2 ? argv[1] : (char*)"Scan_Image0022.jpg";
    src = imread("test_opencv.jpg");
imread( filename );
    if (src.empty())
    {
        return -1;
    }

    int scale = 4;
    cvtColor( src, src_gray, COLOR_BGR2GRAY );
    resize(src_gray,src_gray,Size(src_gray.cols/scale,src_gray.rows/scale )); // optionally resize image to speed up the process

    rectangle(src_gray,Rect(5,5,src_gray.cols-10,src_gray.rows-10),Scalar(0),4); // correction 1
    src_gray = src_gray >127;

    vector<vector<Point> > contours;

    for( int i = 2 ; i < src_gray.cols/2   ; i++ )
    {
        cv::Mat kernel = cv::Mat::ones(i, i, CV_8U);
        erode(src_gray,eroded, kernel);

        findContours( eroded, contours, RETR_LIST, CHAIN_APPROX_SIMPLE, Point(0, 0) );
        if( contours.size()== 1 & contours[0].size() < 5 )
        {
            resize(kernel,kernel,Size(),0.9,0.9); // correction 2
            dilate(eroded,eroded, kernel);
            findContours( eroded, contours, RETR_LIST, CHAIN_APPROX_SIMPLE, Point(0, 0) );
            polylines( src, Mat( contours[0] ) * scale, true, Scalar(0,0,255)); // resize up the contour and draw
            break;
        }
    }
    imshow( "result", src );

    waitKey(0);
    return(0);
}

resized result image:

image description