void find_squares(Mat& image, vector<vector<Point> >& squares)
{
Mat blurred(image);
medianBlur(image, blurred, 9);
Mat gray0(blurred.size(), CV_8U), gray;
for
(int c = 0; c < 3; c++)
{
int ch[] = {c, 0};
mixChannels(&blurred, 1, &gray0, 1, ch, 1);
const
int threshold_level = 2;
for
(int l = 0; l < threshold_level; l++)
{
if
(l == 0)
{
Canny(gray0, gray, 10, 20, 3);
dilate(gray, gray, Mat(), Point(-1, -1));
}
else
{
gray = gray0 >= (l + 1) * 255 / threshold_level;
}
vector<vector<Point> > contours;
findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);
vector<Point> approx;
for
(size_t i = 0; i < contours.size(); i++)
{
approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true) * 0.02, true);
if
(approx.size() == 4
&&
abs
(contourArea(Mat(approx))) > 1000
&& isContourConvex(Mat(approx)))
{
double maxCosine = 0;
for
(int j = 2; j < 5; j++)
{
double cosine = fabs(angle(approx[j % 4], approx[j - 2], approx[j - 1]));
maxCosine = MAX(maxCosine, cosine);
}
if
(maxCosine < 0.3)
squares.push_back(approx);
}
}
}
}
}