用例:
std::vector<std::vector<cv::Point>> contours;
std::vector<cv::Vec4i> hierachy;
cv::findContours(binary, contours, hierachy, cv::RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(-1,-1));
std::vector<std::vector<cv::Point>> contours_ploy(contours.size());
for(int i=0; i<contours.size(); i++)
{
approxPolyDP(contours[i], contours_ploy[i], contours[i].size() / 4, true);
}
参考:opencv 多边形拟合
一、逼近多边形
逼近多边形,是通过对轮廓外形无限逼近,删除非关键点、得到轮廓的关键点,不断逼近轮廓真实形状的方法,OpenCV中多边形逼近的函数与参数解释如下:
approxCourve= cv2.approxPolyDP(curve,epsilon,closed)
参数解析:
curve:轮廓点的集合。
epsilon:指定近似精度的参数, 这是原始曲线和它的近似之间最大距离。
closed:如果为true,则闭合近似曲线(其第一个和最后一个顶点为连接的);否则,不闭合。
二、参考代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#author:Kong DeXing
#案例:Fu Xianjun. All Rights Reserved.
import cv2
import numpy as np
img = cv2.imread('hand.png')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,binary = cv2.threshold(gray,60,255,0)#阈值处理
contours,hierarchy = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)#查找轮廓
print(len(contours))
x = 0
for i in range(len(contours)):
area = cv2.contourArea(contours[i])
if area>10000:
print(area)
x = i
cnt = contours[x]
img1 = img.copy()
approx1 = cv2.approxPolyDP(cnt,3,True)#拟合精确度
img1 =cv2.polylines(img1,[approx1],True,(255,255,0),2)
cv2.imshow('approxPolyDP1',img1)
img2 = img.copy()
approx2 = cv2.approxPolyDP(cnt,5,True)#拟合精确度
img2 =cv2.polylines(img2,[approx2],True,(255,255,0),2)
cv2.imshow('approxPolyDP2',img2)
img3 = img.copy()
approx3 = cv2.approxPolyDP(cnt,7,True)#拟合精确度
img3 =cv2.polylines(img3,[approx3],True,(255,255,0),2)
cv2.imshow('approxPolyDP3',img3)
cv2.imwrite("dst.png",img1)
print(len(approx1))
cv2.waitKey(0)
cv2.destroyAllWindows()
可以看到,cv.approxPolyDP 函数 参数2(epsilon)越小,得到的多边形角点越多,对原图像的多边形近似效果越好。