0

I need to detect all rectangles in image.

Here is my code:

Mat PolygonsDetection(Mat src)
 {
    Mat gray;
    cvtColor(src, gray, CV_BGR2GRAY);

    Mat bw;
    Canny(src, bw, 50, 200, 3, true);
    imshow("canny", bw);

    morphologyEx(bw, bw, MORPH_CLOSE, cv::noArray(),cv::Point(-1,-1),1);

    imshow("morph", bw);

    vector<vector<Point>> countours;
    findContours(bw.clone(), countours, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);

    vector<Point> approx;
    Mat dst = src.clone();

    for(int i = 0; i < countours.size(); i++)
    {
        approxPolyDP(Mat(countours[i]), approx, arcLength(Mat(countours[i]), true) * 0.01, true);

        if (approx.size() >= 4 && (approx.size() <= 6))
        {
            int vtc = approx.size();
            vector<double> cos;
            for(int j = 2; j < vtc + 1; j++)
                cos.push_back(Angle(approx[j%vtc], approx[j-2], approx[j-1]));

            sort(cos.begin(), cos.end());

            double mincos = cos.front();
            double maxcos = cos.back();

            if (vtc == 4)// && mincos >= -0.5 && maxcos <= 0.5)
            {
                Rect r = boundingRect(countours[i]);
                double ratio = abs(1 - (double)r.width / r.height);

                line(dst, approx.at(0), approx.at(1), cvScalar(0,0,255),4);
                line(dst, approx.at(1), approx.at(2), cvScalar(0,0,255),4);
                line(dst, approx.at(2), approx.at(3), cvScalar(0,0,255),4);
                line(dst, approx.at(3), approx.at(0), cvScalar(0,0,255),4);
                SetLabel(dst, "RECT", countours[i]);
            }
        }
    }

    return dst;
 }

Here is my output:

enter image description here

Instead 17 rectangles(16 little and 1 big) I got only 12 rectangles. I'm new in opencv, maybe I pass wrong parameters to Canny function and morphologyEx... So, my questions: What's wrong I do? How do I repair it?

Rougher
  • 834
  • 5
  • 19
  • 46
  • Try playing around with the Canny parameters; the first and particularly the second threshold. Something like `Canny(src, bw, 50, 100, 3, true);` will probably get you there. – HugoRune Apr 12 '14 at 10:28
  • It's not dublicate. I checked that solution and it's not working. – Rougher Apr 12 '14 at 10:42

1 Answers1

0

What you can do is use the usual erode dilate trick. In Matlab, I usually do the following for creating a mask. This makes lines bigger and flow together.

%Create Structuring element
sel = strel('disk', 1);
% bw is the black and white (binary image) created using e.g. Otsu thresholding
bw2 = imcomplement(bw);
bw3 = imerode(bw2, sel);
bw4 = imdilate(bw3, sel);
tightmask = imcomplement(bw4);

I use this very often for finding independent components in an image

Jens Munk
  • 4,627
  • 1
  • 25
  • 40