Skip to content

Instantly share code, notes, and snippets.

@jbgutierrez
Created July 5, 2013 08:09
Show Gist options
  • Save jbgutierrez/5932855 to your computer and use it in GitHub Desktop.
Save jbgutierrez/5932855 to your computer and use it in GitHub Desktop.
Drawing a bounding box around the detected contours of an image
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <algorithm>
#include <iostream>
#include <iterator>
#include <stdio.h>
#include <stdlib.h>
using namespace cv;
using namespace std;
template <class COCiter, class Oiter>
void flatten (COCiter start, COCiter end, Oiter dest) {
while (start != end) {
dest = copy(start->begin(), start->end(), dest);
++start;
}
}
bool replace(string& str, const string& from, const string& to) {
size_t start_pos = str.find(from);
if(start_pos == string::npos)
return false;
str.replace(start_pos, from.length(), to);
return true;
}
int main( int argc, char** argv )
{
char* fname = argv[1];
/// Read input file
Mat src = imread( fname, 1 );
/// Detect edges using canny
Mat canny_output;
int thresh = 20;
Canny( src, canny_output, thresh, thresh*2, 3 );
/// Find contours
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours( canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );
/// Detect bounding box
vector<Point> flatten_contours;
flatten(contours.begin(), contours.end(), back_inserter(flatten_contours));
RotatedRect rrect = minAreaRect(Mat(flatten_contours));
/// Draw bounding box
Point2f vertices[4];
rrect.points(vertices);
Rect rect = rrect.boundingRect();
rectangle(src, rect, Scalar(255,0,0));
cout << fname << " [" << rect.width << " x " << rect.height << " from (" << rect.x << ", " << rect.y << ")]\n";
/// Uncomment for debugging purposes
string path = string(fname);
replace(path, "input", "output");
imwrite(path, src);
return(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment