Ask Your Question

# Split contours into many small rectangles As the graph show, the most easiest solution is return a bounding rect surrounded the contour, split the bounding rect to small rectangles, but it is much harder for irregular shape.What kind of algorithm would you suggest to split the contour? edit retag close merge delete

## 1 answer

Sort by » oldest newest most voted Simply you can do with the following steps,

• Find contour.
• Draw contour with thickness=CV_FILLED in to a new Mat.
• Find bounding Rect for each contour.
• With in bounding Rect set ROI with your small box size and count non zero pixel.
• Scan the whole bounding rect and check the non-zero pixel count greater than the threshold, if so draw the rectangle.
• Continue the the process for next contour.

The below code shows how to do this, adjust the box size and threshold according to your need.

Mat src=imread("img.png",1);
Mat tmp,thr;
cvtColor(src,tmp,CV_BGR2GRAY);
threshold(tmp,thr,200,255,THRESH_BINARY_INV);

vector< vector <Point> > contours;
vector< Vec4i > hierarchy;
Mat dst(src.rows,src.cols,CV_8UC1,Scalar::all(0));//Ceate Mat to draw contour

int box_w=10; // Define box width here
int box_h=10; // Define box height here
int threshold_perc=25; //perceantage value for eliminating the box according to pixel count inside the box
int threshold=(box_w*box_h*threshold_perc)/100;

findContours( thr, contours, hierarchy,CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE ); //Find contour

for( int i = 0; i< contours.size(); i++ ){
drawContours( dst,contours, i, Scalar(255,255,255),CV_FILLED, 8, hierarchy ); // Draw contour with  thickness = filled
Rect r= boundingRect(contours[i]); // Find bounding rect

// Scan the image with in bounding box
for(int j=r.x;j<r.x+r.width;j=j+box_w){
for(int k=r.y;k<r.y+r.height;k=k+box_h){
Rect roi_rect(j,k,box_w,box_h);
Mat roi = dst(roi_rect);
int count = countNonZero(roi);
if(count > threshold)
rectangle(src, roi_rect, Scalar(255,0,0),1,8,0 );
}
}
}
imshow("src",src);
waitKey();


Source Image:- Contour :- Result:- more

Official site

GitHub

Wiki

Documentation

## Stats

Asked: 2013-12-27 04:52:49 -0500

Seen: 4,186 times

Last updated: Dec 28 '13