Android OpenCV Find Largest Square or Rectangle

James Arnold picture James Arnold · Jul 7, 2013 · Viewed 23.9k times · Source

This might have been answered but I desperately need an answer for this. I want to find the largest square or rectangle in an image using OpenCV in Android. All of the solutions that I found are C++ and I tried converting it but it doesn't work and I do not know where I'm wrong.

private Mat findLargestRectangle(Mat original_image) {
    Mat imgSource = original_image;

    Imgproc.cvtColor(imgSource, imgSource, Imgproc.COLOR_BGR2GRAY);
    Imgproc.Canny(imgSource, imgSource, 100, 100);

    //I don't know what to do in here

    return imgSource;
}

What I am trying to accomplish in here is to create a new image that is based on the largest square found in the original image (return value Mat image).

This is what I want to happen:

1 http://img14.imageshack.us/img14/7855/s7zr.jpg

It's also okay that I just get the four points of the largest square and I think I can take it from there. But it would be better if I can just return the cropped image.

Answer

baci picture baci · Jul 7, 2013

After canny

1- you need to reduce noises with gaussian blur and find all the contours

2- find and list all the contours' areas.

3- the largest contour will be nothing but the painting.

4- now use perpective transformation to transform your shape to a rectangle.

check sudoku solver examples to see the similar processing problem. (largest contour + perspective)