cv::Rect diffBack(const cv::Mat& img, const cv::Mat& imgBack, int blurSize = 10,int nthres = 30)
{
assert(img.channels() == 1);
double fx,fy;
fx = 320.0 / img.cols;
fy = fx;
cv::Mat imgS;
cv::resize(img,imgS,cv::Size(),fx,fy,CV_INTER_AREA);
cv::Mat imgB;
cv::resize(imgBack,imgB,cv::Size(),fx,fy,CV_INTER_AREA);
cv::blur(imgS,imgS,cv::Size(blurSize,blurSize));
cv::blur(imgB,imgB,cv::Size(blurSize,blurSize));
Mat imgSubt;
cv::subtract(imgS,imgB,imgSubt);
if(horizeShow)
{
imshow("diffBack-subtract",imgSubt);
}
Mat imgT;
cv::threshold(imgSubt,imgT,nthres,255,CV_THRESH_BINARY);
cv::RotatedRect box;
if(maxBoundingBox(imgT,box))
{
if(horizeShow)
{
cv::Mat imgShow;
imgShow.create(imgS.rows,imgS.cols,CV_8UC3);
cv::vector<cv::Mat> imgChannels;
imgChannels.push_back(imgS);
imgChannels.push_back(imgS);
imgChannels.push_back(imgS);
cv::merge(imgChannels,imgShow);
cv::Point2f vtx[4];
box.points(vtx);
for(int i = 0; i < 4; i++ )
{
line(imgShow, vtx[i], vtx[(i+1)%4], Scalar(0, 255, 0), 1, CV_AA);
}
cv::imshow("MaxBoundingBox2.bmp",imgShow);
waitKey();
}
box.center.x = box.center.x / fx;
box.center.y = box.center.y / fy;
box.size.width = box.size.width / fx;
box.size.height = box.size.height / fy;
cv::Rect rect1 = box.boundingRect();
if(rect1.x < 0)
rect1.x = 0;
if(rect1.y < 0)
rect1.y = 0;
if((rect1.width + rect1.x)>img.cols)
rect1.width = img.cols - rect1.x;
if((rect1.height + rect1.y)>img.rows)
rect1.height = img.rows - rect1.y;
return rect1;
}
else return Rect();
}
将2560*1920的8位灰度图缩放到320*240,平均模糊10x10,耗时50ms
56 43 59 57 54 50 42 41 46 40 35 46 42 40 51 45 41 44 68 40 46 42 62