Ask Your Question
2

Split contours into many small rectangles

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

stereoMatching gravatar image

updated 2015-11-18 15:05:48 -0500

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?

image description

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
6

answered 2013-12-28 08:01:40 -0500

Haris gravatar image

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:-

image description

Contour :-

image description

Result:-

image description

edit flag offensive delete link more
Login/Signup to Answer

Question Tools

1 follower

Stats

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

Seen: 3,625 times

Last updated: Dec 28 '13