I am trying to detect rectangular shapes on a sample image with the following code in cpp. I have a list that holds objects of the type cv::Rect then I use a method called cv::findContours() to try and detect all the contours from a gray scale image. I then loop through each contour detected and check if it qualifies to be a rectangle and push it to my list. I then loop through the list of rectangles and draw over them and save the final image to disk. The code is able to draw over all the shapes detected over the image with edges but does not draw a thing over the original color image. How do I draw over the shapes detected over the original image and save to hard drive.
Please the code below for more information on my attempt at this.
cv::Mat image ;
cv::Mat edges;
image = cv::imread(name, cv::IMREAD_GRAYSCALE);
//call the function to detect the edges
cv::Canny(image, edges, 200, 200);
//save the image
cv::imwrite("edges.png", edges);
//declare a new shape for detecting the shapes from the edged image
std::vector<std::vector<cv::Point>> contours;
cv::Mat input = cv::imread("edges.png", cv::IMREAD_GRAYSCALE);
//detect contors from the image
cv::findContours(input, contours, cv::RETR_LIST, cv::CHAIN_APPROX_SIMPLE);
//list to hold the rectangular contours
std::list<cv::Rect> rects;
//iterate through the contours
for (int i = 0;i < contours.size();i++) {
std::vector<cv::Point> approx = std::vector<cv::Point>();
//check if the contour is rectangular
cv::approxPolyDP(contours[i], approx, cv::arcLength(contours[i], true) * 0.02, true);
if (approx.size() == 4) {
//this contour is rectangular, get the bounding rect and add to a list
cv::Rect rect = cv::boundingRect(contours[i]);
//add the rect to a list
rects.push_back(rect);
}
}
if (rects.size() > 0) {
for (std::list<cv::Rect>::iterator it = rects.begin();it != rects.end();++it) {
//get the rect
cv::Rect rect = *it;
cv::rectangle(input, rect, cv::Scalar(250, 128, 114), 5);
}
//save the final image
cv::imwrite("shapes.png", input);
}