Ask Your Question

how to draw rectangles from find countours

asked 2013-12-05 04:09:32 -0500

akoo gravatar image

Hi all, I'm doing a project where i obtain contours of an image and draw the rectangle of minimum area which contains that contours. Now I would like to draw only some rectangles, I would like to avoid rectangles with small area for having a better detection, but I don't know how to draw only the greater rectangles obtained. As you can see in the attached image I would like to draw only the rectangles that contain some character. Some help would be appreciated. Thanks in advance.

I attach the code I have for finding contours and draw the rectangles, as well as the image obtained.

Mat encuentraRect(Mat imagen){


Mat threshold_output;

vector<vector<Point> > contours;

vector<Vec4i> hierarchy;

/// Detect edges using Threshold
threshold( imagen, threshold_output, 100, 255, THRESH_BINARY );
/// Find contours
findContours( threshold_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );

/// Find the rotated rectangles for each contour
vector<RotatedRect> minRect( contours.size() );

for( uint i = 0; i < contours.size(); i++ ){
    minRect[i] = minAreaRect( Mat(contours[i]) );


/// Draw contours + rotated rects
Mat drawing = Mat::zeros( threshold_output.size(), CV_8UC3 );
for( uint i = 0; i< contours.size(); i++ ){
    Scalar red(0,0,255) ;
    Scalar white(255,255,255);
    // contour
    drawContours( drawing, contours, i, white, 1, 8, vector<Vec4i>(), 0, Point() );

    // rotated rectangle
    Point2f rect_points[4];
    minRect[i].points( rect_points );
    float angle;

    for( int j = 0; j < 4; j++ ){
        line(region , rect_points[j], rect_points[(j+1)%4], red, 1, 8 );

return region;

} image description

edit retag flag offensive close merge delete

1 answer

Sort by ┬╗ oldest newest most voted

answered 2013-12-05 06:47:51 -0500

bpp gravatar image

updated 2013-12-11 11:12:56 -0500

Using the coordinates you could compute the area of each rectangle and then threshold on it.

area = (abs(x1-x0) * abs(y1-y0));

if(area>threshold) draw

You should check the index used to compute the width and the height of the rectangle because I'm not sure of the order returned by the function that find rectangles.

edit flag offensive delete link more


Thanks berak, it was wrong. Yes with ^ I meant pow not bitwise xor.

bpp gravatar imagebpp ( 2013-12-11 11:16:19 -0500 )edit

Question Tools


Asked: 2013-12-05 04:09:32 -0500

Seen: 1,867 times

Last updated: Dec 11 '13