similar images with different contours

asked 2014-10-08 01:18:33 -0500

HasanGhaforian gravatar image

I have to detect sheet edges in Android App.So I follow these steps:

  1. convert image to gray
  2. using Imgproc.Canny to detect it's edges and get binary image.
  3. using Imgproc.findContours to find largest contour.

As you see,I do not use bluring or adaptive thresholding,because if I use them the result will be very bad on some images.This is my snippet of code:

Mat src = new Mat();
Utils.bitmapToMat(bmp, src);
Imgproc.cvtColor(src, src, Imgproc.COLOR_RGBA2GRAY);

// Detect the edges of the image by using a Canny detector:
Imgproc.Canny(src, src, 50, 200);

List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
Mat hierarchy = new Mat();
// find contours:
Imgproc.findContours(src, contours, hierarchy, Imgproc.RETR_TREE,
double largestArea = 0;
int largestIndex = 0;
// find largest contour:
for (int contourIdx = 0; contourIdx < contours.size(); contourIdx++) {
    double currentArea = Imgproc.contourArea(contours.get(contourIdx));
    if ((currentArea > 100) && (currentArea > largestArea)) {
        largestIndex = contourIdx;
        largestArea = currentArea;
// fill largest contour:
Imgproc.drawContours(src, contours, largestIndex, new Scalar(100), -1);

Bitmap tempBmp1 = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(),

Utils.matToBitmap(src, tempBmp1);

I test that on two images.You can see edge detected(after using Canny) result of those here:

image description

image description

Both are similar,because both are images of the same paper that is rotated and on different background.I expect largest contour of both must be same,but result is strange:

image description

image description

My questions are:

  1. why result of largest contour is so different,while result of Canny are similar?
  2. How I can change the code to get better result on most of images (not only on vertical image that is presented above)?

I do not want to use houghlines because it's time is very long and has very calculation.

edit retag flag offensive close merge delete


it could be the lightning. The Canny is returning a closed contour on the first case, so the largest contour is not the rectangle, but the I do not know what line. Maybe you can do a small improvement using morphology operations

thdrksdfthmn gravatar imagethdrksdfthmn ( 2014-10-08 03:46:35 -0500 )edit

The reason why your canny is so sensitive is exactly due to not wanting to blur with a Gaussian filter and not applying histogram equalization. Your canny will respond to every little pixel change, leading to a very unpredictable result ... I think you should reconsider the filters mentioned. As to HoughLines being long calculation time, not true, use it effectively (by setting strict parameters) and you can process easily at 30 FPS. A possible approach was already mentioned here.

StevenPuttemans gravatar imageStevenPuttemans ( 2014-10-08 04:02:07 -0500 )edit