Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Hi.

Another way could be to find the contours by thresholding your image (if all your images look binary) and finding the bounding rectangle for each contour.

In C++, using the tutorial: Creating Bounding boxes and circles for contours

#include <iostream>

#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

using namespace cv;
using namespace std;


//See http://docs.opencv.org/doc/tutorials/imgproc/shapedescriptors/bounding_rects_circles/bounding_rects_circles.html
int main( int argc, char** argv )
{
    Mat img = imread("crop_rectangle.png", CV_LOAD_IMAGE_GRAYSCALE);

    Mat threshold_output;
    /// Detect edges using Threshold
    threshold( img, threshold_output, 20, 255, THRESH_BINARY );

    imshow( "threshold_output", threshold_output );

    vector<vector<Point> > contours;
    vector<Vec4i> hierarchy;
    /// Find contours
    findContours( threshold_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );

    /// Approximate contours to polygons + get bounding rects
    vector<vector<Point> > contours_poly( contours.size() );
    Rect boundRect;

    double maxArea = 0.0;
    for( int i = 0; i < contours.size(); i++ )
    { 
        double area = contourArea(contours[i]);
        if(area > maxArea) {
            maxArea = area;
            approxPolyDP( Mat(contours[i]), contours_poly[i], 3, true );
            boundRect = boundingRect( Mat(contours_poly[i]) );
        }
    }

    Mat cropImage = img(boundRect);
    imshow("cropImage", cropImage);

    waitKey(0);
    return(0);
}