I've been trying to find the best way to detect the 4 black squares on the paper and use them to isolate the paper in its own image.
Asked
Active
Viewed 4,587 times
7
-
Welcome to StackOverflow. What have you tried so far that isn't working for you? Have you looked at [this question](http://stackoverflow.com/q/11424002/62576) to see if it helps? Please show some effort to solve this yourself (other than posting an image), and someone here can probably help. – Ken White Jul 17 '12 at 23:23
1 Answers
9
It seems that on your image there are only 4 black squares so what you have to do is:
- Convert image to grays
- Do threshold
- Find black contours (before doing this in OpenCV you have to invert your image, because by default OpenCV finds white contours)
- Cycle through these contours and find bounding rectangle.
Do the check:
A) Rectangle's area is bigger that some constant (in my solution it was 100)
B) Rectangle's width/height is near 1.0 (in my soultion it was [0.9, 1.1] range)
The code:
Mat img = imread("test.jpg"), gray;
vector<Vec4i> hierarchy;
vector<vector<Point2i> > contours;
cvtColor(img, gray, CV_BGR2GRAY);
threshold(gray, gray, 100, 255, THRESH_BINARY);
bitwise_not(gray, gray);
findContours(gray, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
for(size_t i=0; i<contours.size(); i++)
{
Rect rect = boundingRect(contours[i]);
double k = (rect.height+0.0)/rect.width;
if (0.9<k && k<1.1 && rect.area()>100)
{
drawContours(img, contours, i, Scalar(0,0,255));
}
}
imshow("result", img);
waitKey();
Result:
Also read this SO discussion - you don't need that 4 squares to detect paper.

Community
- 1
- 1

ArtemStorozhuk
- 8,715
- 4
- 35
- 53