只用来记录学习笔记
Mat src, gray_src, temp, dst;
const char* input_title = "input";
const char* output_title = "output";
const char* trackbar_title = "output";
int threshold_value = 80;
int threshold_max = 255;
RNG rng(12345);
void Demo_Moments(int,void*);
cvtColor(src, gray_src, CV_BGR2GRAY); //转灰度图像
GaussianBlur(gray_src, gray_src, Size(3, 3), 0,0); //高斯模糊
createTrackbar(trackbar_title, output_title, &threshold_value, threshold_max, Demo_Moments);//滑块改变阈值
Demo_Moments(0, 0);
void Demo_Moments(int, void*) {
Mat canny_output;
vector<vector<Point>> contours; //轮廓
vector<Vec4i> hierachy;
Canny(gray_src, canny_output, threshold_value, threshold_value * 2, 3, false); //边缘检测
findContours(canny_output, contours, hierachy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(-1, -1));//轮廓发现
vector<Moments> contours_moments(contours.size());
vector<Point2f> ccs(contours.size());
for (size_t i = 0; i < contours.size(); i++) { //循环遍历轮廓
contours_moments[i] = moments(contours[i]);//中心距
ccs[i] = Point(static_cast<float>(contours_moments[i].m10 / contours_moments[i].m00), static_cast<float>(contours_moments[i].m01 / contours_moments[i].m00));//圆心
}
Mat drawimg;
src.copyTo(drawimg);
for (size_t i = 0; i < contours.size(); i++) {
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
cout << "contours " << i << "area: " << contourArea(contours[i]) << "are length:" << arcLength(contours[i],false) << endl;
//contourArea轮廓面积算法;
//arcLength:计算封闭轮廓的周长或曲线的长度
drawContours(drawimg, contours, i, color, 2, 8, hierachy, 0, Point(0, 0));//绘制轮廓
circle(drawimg, ccs[i], 2, color, 2, 8); //绘制圆心
}
imshow(output_title, drawimg);
return;
}