approxPolyDP(拟合多边形)
2019-08-22 本文已影响0人
itfitness
概念
把一条平滑的曲线曲折化。
如下图所示,原来有A、B、C三个点的折线,拟合后变成A、C两点。
效果图对比
●图像原轮廓
●拟合后的轮廓
函数讲解
●函数原型(findContours)
○c++
void approxPolyDP( InputArray curve,
OutputArray approxCurve,
double epsilon, bool closed )
○Android
void approxPolyDP(MatOfPoint2f curve, MatOfPoint2f approxCurve, double epsilon, boolean closed)
●参数解释
○curve:图像的轮廓点组成的点集。
○approxCurve:输出多边形的点集。
○epsilon:主要表示输出的精度;这是原始曲线与其近似之间的最大距离,数值越大边数越少。
○closed :表示输出的多边形是否封闭;true表示封闭,false表示不封闭。
函数使用
●c++中
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace cv;
using namespace std;
int main() {
Mat src = imread("C:/Users/Administrator/Desktop/m01.png");//引入源图像
if (src.empty()) {
return -1;
}
cvtColor(src,src,CV_BGR2GRAY);//图像灰度化
threshold(src,src,100,255,CV_THRESH_BINARY_INV);//图像二值化
vector<vector<Point>> contours;//存储图像轮廓点集
findContours(src,contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);//查找轮廓
Scalar lineColor = Scalar(0, 255, 255);//绘制线的颜色为黄色
Mat contoursMat = Mat::zeros(src.size(),CV_8UC3);//图像原轮廓
//绘制轮廓
drawContours(contoursMat, contours, -1, lineColor, 2, 8);
imshow("contours", contoursMat);//展示图像原轮廓
vector<vector<Point>> lines(contours.size());//存储拟合多边形点集
Mat dst = Mat::zeros(src.size(),CV_8UC3);
//拟合多边形
for (int i = 0; i < contours.size(); i++) {
//拟合
approxPolyDP(contours[i],lines[i],9,true);
}
//绘制拟合后的多边形
drawContours(dst, lines, -1,lineColor,2,8 );
imshow("dst", dst);//展示拟合后的轮廓
waitKey(0);
return 0;
}
●Android中
private Bitmap approxPolyDP() {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.m01);//引入源图像
Mat src = new Mat();
Utils.bitmapToMat(bitmap, src);//将Bitmap转为Mat
Imgproc.cvtColor(src,src,Imgproc.COLOR_RGBA2GRAY);//图像灰度化
Imgproc.threshold(src, src, 100, 255, Imgproc.THRESH_BINARY_INV);//图像二值化
Mat dst = Mat.zeros(src.size(), CvType.CV_8UC4);//创建黑色纯色图像,大小与源图像一样
Mat hierarchy = new Mat();
ArrayList<MatOfPoint> contours = new ArrayList<>();//存储图像轮廓的点集
Imgproc.findContours(src, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE);//提取轮廓
ArrayList<MatOfPoint> approxCurves = new ArrayList<>();//存取拟合多边形的点集
for(MatOfPoint point : contours) {
MatOfPoint2f curvesPoint = new MatOfPoint2f(point.toArray());//将MatOfPoint转为MatOfPoint2f
MatOfPoint2f approxCurvesPoint = new MatOfPoint2f();
Imgproc.approxPolyDP(curvesPoint,approxCurvesPoint,8,true);//拟合
MatOfPoint newPoint = new MatOfPoint(approxCurvesPoint.toArray());//将MatOfPoint2f转为MatOfPoint
approxCurves.add(newPoint);
}
Imgproc.drawContours(dst,approxCurves,-1,new Scalar(255,255,0),2,8);//绘制拟合后的多边形
Utils.matToBitmap(dst,bitmap);//将Mat转为Bitmap
return bitmap;
}