opencv学习笔记29-图像矩

只用来记录学习笔记

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;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值