作者:安安1 | 来源:互联网 | 2023-05-18 20:35
惯例先放结果吧
imshow("原图", 原图);
Mat 灰度图,二值图;
cvtColor(原图, 二值图, CV_BGR2GRAY);
//blur(灰度图, 二值图, Size(5, 5));//模糊一下,可以不要
threshold(二值图, 二值图, 0, 255, CV_THRESH_OTSU);//自适应二值化
二值图 = 255 - 二值图;//颜色反转
//imshow("二值图", 二值图);
//寻找最外层轮廓
vector> contours;
vector hierarchy;
findContours(二值图, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_NONE, Point());
Mat 画布 = Mat::zeros(二值图.size(), CV_8UC1); //最小外接矩形画布
for (int i = 0; i {
//绘制轮廓
drawContours(画布, contours, i, Scalar(255), 1, 8, hierarchy);
//绘制轮廓的最小外结矩形
RotatedRect rect = minAreaRect(contours[i]);
//rectangle(画布,rect.boundingRect(),Scalar(55));
Point2f P[4];
rect.points(P);
for (int j = 0; j <= 3; j++)
{
line(原图, P[j], P[(j + 1) % 4], Scalar(0,0,255), 1);
line(画布, P[j], P[(j + 1) % 4], Scalar(111), 2);
}
/*
//绘制轮廓的最小外结圆
Point2f center; float radius;
minEnclosingCircle(contours[i], center, radius);
circle(画布1, center, radius, Scalar(255), 2);
*/
}
//imshow("最小外接矩形", 画布);
imshow("标注出矩形", 原图);
waitKey(0);
return 0;
}