欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

OpenCV实践:计算轮廓的面积和周长

程序员文章站 2022-05-20 19:39:20
...

1、对如下图片的面积与周长进行测量

OpenCV实践:计算轮廓的面积和周长

2、算法思路

  1. 灰度处理
  2. 模糊处理
  3. 二值化
  4. 形态学处理
  5. 最大轮廓检测
  6. 计算面积与周长

3、代码实践

# include<opencv2\opencv.hpp>
# include <iostream>
using namespace std;
using namespace cv;

int main(int argc, char** argv) {
	Mat src, dst, gray_src;
	src = imread("D://05.jpg");
	if (src.empty()) {
		cout << "can't find this picture...";
		return -1;
	}
	imshow("input", src);
	cvtColor(src, gray_src, COLOR_BGR2GRAY);
	//高斯模糊
	Mat blurImage;
	GaussianBlur(gray_src, blurImage, Size(15, 15), 0, 0);
	imshow("Gauss blur", blurImage);
	//二值化
	Mat binaryImage;
	threshold(blurImage, binaryImage, 0, 255, THRESH_BINARY | THRESH_TRIANGLE);
	imshow("binary image", binaryImage);
	//形态学处理
	Mat morphlogyImage;
	Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));
	morphologyEx(binaryImage, morphlogyImage, MORPH_CLOSE, kernel, Point(-1, -1), 2);
	imshow("close Image", morphlogyImage);
	//获取最大轮廓
	Mat ResultImage = Mat::zeros(src.size(), CV_8UC3);
	vector<vector<Point>> contours;
	vector<Vec4i>hierchy;
	findContours(morphlogyImage, contours, hierchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point());//这里用RETR_EXTERNAL显示最外层轮廓,而TREE显示所有轮廓,背景像素要是黑色
	for (size_t t = 0; t < contours.size(); t++) {
		Rect rect = boundingRect(contours[t]);
		if (rect.width < src.cols / 2) continue;
		if (rect.width >(src.cols - 20)) continue;
		double area = contourArea(contours[t]);
		double lenth = arcLength(contours[t], true);
		drawContours(ResultImage, contours, static_cast<int>(t), Scalar(0, 0, 255), 2, 8, Mat());
		printf("area:%f\n", area);
		printf("lenth:%f\n", lenth);
	}
	imshow("ResultImage", ResultImage);
	waitKey(0);
	return 0;
}

OpenCV实践:计算轮廓的面积和周长

OpenCV实践:计算轮廓的面积和周长

OpenCV实践:计算轮廓的面积和周长

相关标签: opencv