Ask Your Question

Crop image, after border detection

asked 2015-04-19 15:06:30 -0600

Gonzalo gravatar image

Hello!! I'm coding in Java. I'm manipulating an image and the result till now is this:

image description

As you can see, I found a region surrounded by the white line using Imgproc.drawContours().

Now I want to be able to crop the image taking only the internal area of the shape, discarding the rest.

Ho can I solve the problem?

edit retag flag offensive close merge delete


Hi, may be you can use houghline to detect line and to find 4 coners position.

wuling gravatar imagewuling ( 2015-04-19 19:00:08 -0600 )edit

can you tell me how to use houghline to find the 4 corners? do you have a java example?

Gonzalo gravatar imageGonzalo ( 2015-04-20 09:48:41 -0600 )edit

1 answer

Sort by ยป oldest newest most voted

answered 2015-04-19 20:15:08 -0600

Eduardo gravatar image


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;

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);

edit flag offensive delete link more

Question Tools

1 follower


Asked: 2015-04-19 15:06:30 -0600

Seen: 13,615 times

Last updated: Apr 19 '15