Question

I ve got a binary mat file, which contain only black and white pixel. Basically is a body extraction mask and I want to calculate the bounding box. How can I calculate the min and max white value from that binary image in order to calculate the bouding box of the shapped calculated? My code:

Mat bodyEx(string filename){

cv::Mat matInput=cv::imread(filename);

//Set mask
cv::Mat matMask = cv::Mat::ones(matInput.size(), CV_8U) * cv::GC_BGD;
cv::Rect area;
area.x=int(matInput.cols*0.1);  area.y=int(matInput.rows*0.05);
area.width=int(matInput.cols-2*area.x);
area.height=int(matInput.rows-2*area.y);
rectangle(matMask, area , cv::Scalar(cv::GC_PR_FGD),-1,8,0);
area.x=int(matInput.cols*0.35); area.y=int(matInput.rows*0.25);
area.width=matInput.cols-2*area.x;
area.height=matInput.rows-2*area.y;
rectangle(matMask, area , cv::Scalar(cv::GC_FGD),-1,8,0);

//Segmentation
cv::Mat bgd,fgd;
cv::grabCut(matInput, matMask, area, bgd, fgd, 1, cv::GC_INIT_WITH_MASK);
matMask= matMask&1;
cv::compare(matMask,cv::GC_FGD,matMask,cv::CMP_EQ);
cv::Mat matSegmented=cv::Mat::zeros(matInput.size(),CV_8UC3);
matInput.copyTo(matSegmented,matMask);


int lowestWhite_x;  int lowestWhite_y;
cout << "Rows " << matMask.rows << " and cols: "<< matMask.cols << endl;
for (int row=0;row<matMask.rows;row++) 
    { 
       for (int col=0;col<matMask.cols;col++) 
        {
            if(matMask.at<uchar>(row,col) != 0){lowestWhite_x = row; lowestWhite_y = col;}
        } 
    }

cout << "Rows " << lowestWhite_x << " and cols: "<< lowestWhite_y << endl;
//Display
/*cv::imshow("InputImage",matInput);
cv::imshow("mask",matMask);
cv::imshow("Segmented",matSegmented);
cvWaitKey();*/

return matSegmented;

}

EDIT:

Rect faceRect, brect;
std::vector<std::vector<cv::Point> > contours;
std::vector<cv::Vec4i> hierarchy;
cv::findContours( matMask, contours, hierarchy, cv::RETR_CCOMP, cv::CHAIN_APPROX_TC89_KCOS);
for ( size_t i=0; i<contours.size(); ++i )
{
    cv::drawContours( matInput, contours, i, Scalar(0,255,0), 1, 8, hierarchy, 0, Point() ); 
    cv::Rect brect = cv::boundingRect(contours[i]);
    cv::rectangle(matInput, brect, Scalar(0,255,0));
    cout << brect.size() << endl;
}

It calculates all the contours. Finally I want to keep the bb. 4 points not all the contours of the image. How can I do so?

Was it helpful?

Solution

Find the contours on the binary image using findContours function and find the bounding rectangle using boundingRect function.

An example of the usage can be found here: How to draw a rectangle around the contours?

Response to your edit: Try Rect myRect = boundingRect(contours[i]); instead of Rect myRect = boundingRect(contours); is wrong.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top