凸轮廓与Douglas-Peucker算法:
大多数处理轮廓的时候,物体的形状(包括凸形状)都是变换多样的。凸形状内部的任意两点的连线都在该形状里面。
cv.approxPloyDP是一个计算进似多边形框的函数,该函数有三个参数:
如果需要轮廓的周长信息可以通过Opencv的cv2.arcLength函数来完成:
epsilon=0.01*cv2.arcLength(cnt,True)
approx=cv2.approxPolyDP(cnt,epsilon,True)
通过OpenCV来有效计算一个近似多变形,多边形周长与源轮廓周长之比就为$\varepsilon$
为了计算图形状,需要用OpenCV的cv2.convexHull函数来获取处理过的轮廓信息,
hull =cv2.convexHull(cnt)
完整代码:
import cv2
import numpy as np
img = cv2.pyrDown(cv2.imread("hammer.jpg", cv2.IMREAD_UNCHANGED))
ret, thresh = cv2.threshold(cv2.cvtColor(img.copy(), cv2.COLOR_BGR2GRAY) , 127, 255, cv2.THRESH_BINARY)
black = cv2.cvtColor(np.zeros((img.shape[1], img.shape[0]), dtype=np.uint8), cv2.COLOR_GRAY2BGR)
image, contours, hier = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
epsilon = 0.01 * cv2.arcLength(cnt,True)
approx = cv2.approxPolyDP(cnt,epsilon,True)
hull = cv2.convexHull(cnt)
cv2.drawContours(black, [cnt], -1, (0, 255, 0), 2)
cv2.drawContours(black, [approx], -1, (255, 255, 0), 2)
cv2.drawContours(black, [hull], -1, (0, 0, 255), 2)
cv2.imshow("hull", black)
cv2.waitKey()
cv2.destroyAllWindows()