问题描述:利用opencv库函数ArcLength()计算轮廓周长时,计算得到周长比实际轮廓周长偏大。
利用opencv库函数ArcLength()计算轮廓周长方法。
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
// 读入图像
Mat src;
src = imread(argv[1], 1);
// 将图像转换为灰度图像
Mat src_gray;
cvtColor(src, src_gray, COLOR_BGR2GRAY);
// 二值化处理
threshold(src_gray, src, 120, 255, THRESH_BINARY);
// 查找轮廓
vector<vector<Point>> contours;
findContours(src, contours, RETR_EXTERNAL, CHAIN_APPROX_NONE);
// 计算轮廓长度
double totalArcLength = 0;
for (size_t i = 0; i < contours.size(); i++) {
double arcLength = arcLength(contours[i], closed);
totalArcLength += arcLength;
cout << "Contour " << i << " length: " << arcLength << endl;
}
cout << "Total arc length: " << totalArcLength << endl;
利用ArcLength()计算下图中圆(半径为100)的周长,得周长为:661.754;
利用圆周长公式计算圆的周长为:100*2*3.14=628;
解决办法:
利用函数approxPolyDP()对所找到轮廓进行多边形拟合,求多边形拟合后轮廓长度,
例:
vector<Point>contoury;//待求轮廓周长
vector<Point>contours_poly;//多边形拟合后轮廓
approxPolyDP(contours, contours_poly, 1, true);//拟合精度选择1
float a = arcLength(contours_poly, true);
利用多边形拟合后,计算长度为:626.975,与实际长度:628,相差0.16%。