Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

how to draw rectangles from find countours

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){

blur(imagen,imagen,Size(3,3));

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 );

    }
}
imwrite("/home/adrian/workspace/OCR_2/resultados/rectangulos.png",region);
return region;
//imshow("contornos",drawing);

} image description