Using a simple combination of blur & threshold I managed to get this result (resized for viewing purposes):
After that, applying erosion & the squares.cpp technique (which is a sample from OpenCV) outputs:
which is almost the result you are looking for: the bottom part of the rectangle was successfully detected. All you need to do is increase the height of the detected rectangle (red square) to fit your area of interest.
Code:
Mat img = imread(argv[1]);
// Blur
Mat new_img = img.clone();
medianBlur(new_img, new_img, 5);
// Perform threshold
double thres = 210;
double color = 255;
threshold(new_img, new_img, thres, color, CV_THRESH_BINARY);
imwrite("thres.png", new_img);
// Execute erosion to improve the detection
int erosion_size = 4;
Mat element = getStructuringElement(MORPH_CROSS,
Size(2 * erosion_size + 1, 2 * erosion_size + 1),
Point(erosion_size, erosion_size) );
erode(new_img, new_img, element);
imwrite("erode.png", new_img);
vector<vector<Point> > squares;
find_squares(new_img, squares);
std::cout << "squares: " << squares.size() << std::endl;
draw_squares(img, squares);
imwrite("area.png", img);
EDIT:
The find_squares()
function returns a vector with all the squares found in the image. Because it iterates on every channel of the image, on your example it successfully detects the rectangular region in each of them, so printing squares.size()
outputs 3
.
As a square can be seen as a vector of 4 (X,Y) coordinates, OpenCV express this concept as vector<Point>
allowing you to access the X and Y part the coordinate.
Now, printing squares
revelead that the points were detected in a counterclockwise direction:
1st ------ 4th
| |
| |
| |
2nd ------ 3rd
Following this example, its fairly obvious that if you need to increase the height of the rectangle you need to change the Y of the 1st and 4th points:
for (int i = 0; i < squares.size(); i++)
{
for (int j = 0; j < squares[i].size(); j++)
{
// std::cout << "# " << i << " " << squares[i][j].x << ","<< squares[i][j].y << std::endl;
if (j == 0 || j == 3)
squares[i][j].y = 0;
}
}