当得到对象轮廓后,可用boundingRect()得轮廓的最外接小正矩形(绿色框),minAreaRect()得到轮廓的最小外接旋转矩形(红色框)。
1)Rect boundingRect(InputArray points)
boundRect[i] = boundingRect(Mat(contours[i])); //最小外接矩形(水平)
//取水平目标框参数
x_t0 = boundRect[i].x;
y_t0 = boundRect[i].y;
w_t0 = boundRect[i].width;
h_t0 = boundRect[i].height;
//画目标框
rectangle(src, Point(boundRect[i].x, boundRect[i].y), Point(boundRect[i].x + boundRect[i].width, boundRect[i].y + boundRect[i].height), Scalar(0, 255, 0), 2, 8);
2)RotatedRect minAreaRect(InputArray points)
box[i] = minAreaRect(Mat(contours[i])); //最小外接矩形(带角度)
box[i].points(rect);//把最小外接矩形四个端点复制给rect数组
//取带角度的目标框
x_t0 = box[i].center.x - (box[i].size.width / 2);
y_t0 = box[i].center.y - (box[i].size.height / 2);
w_t0 = box[i].size.width;
h_t0 = box[i].size.height;
//画目标框
for (int j = 0; j<4; j++) {
line(src, rect[j], rect[(j + 1) % 4], Scalar(0, 0, 255), 2, 8);
}
3)示例:寻找图片中每个目标最小包围矩形
//inImgM:输入照片,outImgM:输出图片
void minRect(Mat &inImgM, Mat &outImgM)
{
Mat src = inImgM.clone();
Mat src_gray, src_canny, dst;
//图像预处理
cvtColor(src, src_gray, COLOR_RGB2GRAY);
GaussianBlur(src_gray, dst, Size(5, 5), 10, 10);
Canny(dst, src_canny, 250, 100, 3);
//imshow("canny检测", src_canny);
Mat element = getStructuringElement(MORPH_RECT, Size(4, 2)); //定义结构元素
dilate(src_canny, src_canny, element); //膨胀
//imshow("膨胀", src_canny);
vector<vector<Point>> contours;
vector<Vec4i> hierarcy;
findContours(src_canny, contours, hierarcy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE); //寻找轮廓
vector<Rect> boundRect(contours.size());
vector<RotatedRect>box(contours.size());
Point2f rect[4];
for (int i = 0; i < contours.size(); i++)
{
box[i] = minAreaRect(Mat(contours[i])); //最小外接矩形(带角度)
boundRect[i] = boundingRect(Mat(contours[i])); //最小外接矩形(水平)
box[i].points(rect);//把最小外接矩形四个端点复制给rect数组
//设置矩形标记阈值
if ((boundRect[i].width < limit_box[0] || limit_box[1] < boundRect[i].width) ||
(boundRect[i].height < limit_box[2] || limit_box[3] < boundRect[i].height))//筛选
continue;
Mat ROI_t;
int x_t0 = 0, y_t0 = 0, w_t0 = 0, h_t0 = 0;
取带角度的目标框
//x_t0 = box[i].center.x - (box[i].size.width / 2) + deviation_x;
//y_t0 = box[i].center.y - (box[i].size.height / 2) + deviation_y;
//w_t0 = box[i].size.width;
//h_t0 = box[i].size.height;
//取水平目标框
x_t0 = boundRect[i].x + deviation_x;
y_t0 = boundRect[i].y + deviation_y;
w_t0 = boundRect[i].width;
h_t0 = boundRect[i].height;
ROI_t = src(Rect(x_t0, y_t0, w_t0, h_t0));
//画目标框
//水平框
rectangle(src, Point(boundRect[i].x, boundRect[i].y), Point(boundRect[i].x + boundRect[i].width, boundRect[i].y + boundRect[i].height), Scalar(0, 255, 0), 2, 8);
//带角度框
for (int j = 0; j<4; j++) {
line(src, rect[j], rect[(j + 1) % 4], Scalar(0, 0, 255), 2, 8);
}
//画中心点
circle(src, Point(box[i].center.x, box[i].center.y), 3, Scalar(0, 0, 255), -1, 8);
imshow("Img1", src);
}
outImgM = src.clone();
}