Ask Your Question
3

Split contours into many small rectangles

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

stereoMatching gravatar image

updated 2020-10-28 02:35:07 -0600

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
7

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

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

Question Tools

1 follower

Stats

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

Seen: 8,379 times

Last updated: Dec 28 '13