因之前的代码很多多余,学习的时候刚写的,现于2018/8/6更新:
源代码如下:
// 操作系统: Windows 10 64
// IDE版本:Visual Studio 2017
// OpenCV版本: 3.4
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include
using namespace cv;
using namespace std;
//找轮廓
void findcontours()
{
vector > g_vContours;
vector g_vHierarchy;
Mat srcimg = imread("1.jpg", 1);
//Rect roi1(424, 315, 2000, 1400);
//srcimg = srcimg(roi1);
cvtColor(srcimg, srcimg, COLOR_BGR2GRAY);
medianBlur(srcimg, srcimg, 5);
threshold(srcimg, srcimg, 100, 255, CV_THRESH_BINARY_INV);
Canny(srcimg, srcimg, 100, 255, 3);
findContours(srcimg, g_vContours, g_vHierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
vector mu(g_vContours.size()); //计算矩
for (unsigned int i = 0; i < g_vContours.size(); i++)
{
mu[i] = moments(g_vContours[i], false);
}
vector mc(g_vContours.size()); //计算中心矩
for (unsigned int i = 0; i < g_vContours.size(); i++)
{
mc[i] = Point2f(static_cast(mu[i].m10 / mu[i].m00), static_cast(mu[i].m01 / mu[i].m00));
}
Mat drawing = Mat::zeros(srcimg.size(), CV_8UC3); //绘制轮廓
for (unsigned int i = 0; i< g_vContours.size(); i++)
{
Scalar color = Scalar(255, 0, 0);
drawContours(drawing, g_vContours, i, color, 2, 8, g_vHierarchy, 0, Point()); //绘制外层和内层轮廓
circle(drawing, mc[i], 4, color, -1, 8, 0);
}
printf("\t 输出内容: 面积和轮廓长度\n"); //输出内容
for (unsigned int i = 0; i< g_vContours.size(); i++)
{
printf(" 通过m00计算出轮廓[%d]的面积: (M_00) = %.2f \n计算出的面积=%.2f , 长度: %.2f \n", i, mu[i].m00, contourArea(g_vContours[i]), arcLength(g_vContours[i], true));
Scalar color2 = Scalar(255, 255, 0);
drawContours(drawing, g_vContours, i, color2, 2, 8, g_vHierarchy, 0, Point());
circle(drawing, mc[i], 4, color2, -1, 8, 0);
}
}
void main()
{
findcontours();
waitKey(0);
system("pause");
}
检测的物体图片:
检测结果: