#include
#include
#include // CV_BGR2GRAY
#include
using namespace std;
using namespace cv;
Mat src01, gray_src01, dst01;
int threshold_v = 170;
int threshold_max = 255;
void contours_callback(int, void*)
{
//二值化
Mat binary_out;
threshold(gray_src01, binary_out, threshold_v, threshold_max, THRESH_BINARY);
vector> contours;
vector hierachy;
findContours(binary_out, contours, hierachy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
imshow("输出图", binary_out);
vector> contours_poly(contours.size());
vector ploy_rects(contours.size());
for (size_t i = 0;i < contours.size();i++)
{
//多边形轮廓
approxPolyDP(contours[i], contours_poly[i], 3, true);
//矩形包围框
ploy_rects[i] = boundingRect(contours_poly[i]);
}
//绘图
src01.copyTo(dst01);
RNG rng(123);
for (size_t t = 0;t < contours.size();t++)
{
Scalar color = Scalar(rng.uniform(0,255), rng.uniform(0, 255), rng.uniform(0, 255));
rectangle(dst01,ploy_rects[t],color,2,8);
}
imshow("矩形框轮廓", dst01);
}
int main01()
{
src01 = imread("C:\Users\dell\Desktop\stuff.jpg");
namedWindow("原图", WINDOW_AUTOSIZE);
namedWindow("输出图", WINDOW_AUTOSIZE);
namedWindow("矩形框轮廓", WINDOW_AUTOSIZE);
cvtColor(src01, gray_src01, CV_BGR2GRAY);
blur(gray_src01, gray_src01, Size(3, 3), Point(-1, -1));
imshow("原图", gray_src01);
createTrackbar("阈值", "输出图", &threshold_v, threshold_max, contours_callback);
contours_callback(0, 0);
waitKey(0);
return 0;
}