opencv计算图像的周长和面积

#include<opencv2/opencv.hpp>
#include<iostream>
#include<math.h>

using namespace cv;
using namespace std;

Mat src;
int main(int argc, char** argv)
{
	src = imread("1.jpg");
	if (src.empty())
	{
		printf("图片未找到!!!");
		return -1;
	}
	imshow("inut image", src);
	//高斯模糊
	Mat GaussImg;
	//medianBlur(src, GaussImg,5);//中值滤波
	GaussianBlur(src, GaussImg, Size(7, 7), 0, 0);//高斯滤波
	imshow("Gauss Image", GaussImg);
	cvtColor(GaussImg, GaussImg, CV_BGR2GRAY);

	//二值化操作
	Mat binary;
	threshold(GaussImg, binary, 0, 255, THRESH_BINARY | THRESH_TRIANGLE);
	imshow("binary Image", binary);

	//形态学操作
	Mat morphImg;
	Mat kernel = getStructuringElement(MORPH_RECT, Size(5, 5), Point(-1, -1));
	morphologyEx(binary, morphImg, MORPH_CLOSE, kernel, Point(-1, -1), 1);
	imshow("morph Image", morphImg);

	//阈值分割
	Mat contoursIm;
	threshold(morphImg, contoursIm, 0, 255, CV_THRESH_BINARY + CV_THRESH_OTSU);
	imshow("阈值分割", contoursIm);

	
	//轮廓发现
	Mat contoursImg = Mat::zeros(src.size(), CV_8UC3);
	vector<vector<Point>>contours;
	vector<Vec4i>hireachy;
	
	findContours(contoursIm, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(-1, -1));
	//findContours(morphImg, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(-1, -1));
	


	for (size_t i = 0; i < contours.size(); i++)
	{
		Rect rect = boundingRect(contours[i]);
		if (rect.width < src.cols / 2)
			continue;

		drawContours(contoursImg, contours, static_cast<int>(i),
			Scalar(0, 0, 255), 2, 8, hireachy, 0, Point(0, 0));
		//计算面积与周长
		float area = contourArea(contours[i]);
		float length = arcLength(contours[i], true);
		printf("对象图像面积为:%f\n", area);
		printf("对象图像周长为:%f\n", length);

	}


	imshow("contours Image", contoursImg);

	waitKey(0);
	return 0;

}


版权声明:本文为weixin_42512266原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。