# OpenCv-C++-小案例实战-对象提取与测量(面积、周长)

1、模糊；
2、二值化；
3、形态学操作；
4、轮廓发现+面积周长计算。

1）高斯模糊

Mat GaussImg;
GaussianBlur(src, GaussImg, Size(7, 7), 0, 0);
imshow("Gauss Image", GaussImg);


2）二值化

Mat binary;
threshold(GaussImg, binary, 0, 255, THRESH_BINARY | THRESH_TRIANGLE);
imshow("binary Image", binary);


3）形态学操作

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


4）轮廓发现

Mat contoursImg=Mat::zeros(src.size(),CV_8UC3);
vector<vector<Point>>contours;
vector<Vec4i>hireachy;
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);


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

using namespace cv;
using namespace std;

Mat src;
int main(int argc, char** argv)
{
if (src.empty())
{
printf("图片未找到!!!");
return -1;
}
imshow("inut image", src);
//高斯模糊
Mat GaussImg;
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 contoursImg=Mat::zeros(src.size(),CV_8UC3);
vector<vector<Point>>contours;
vector<Vec4i>hireachy;
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;

}