凸包講解
凸包跟多邊形逼近很像,只不過它是物體最外層的”凸”多邊形:集合A內連接任意兩個點的直線都在A的內部,則稱集合A是凸形的。如下圖,紅色的部分爲手掌的凸包,雙箭頭部分表示凸缺陷(Convexity Defects),凸缺陷常用來進行手勢識別等:
opencv中凸包函數
# cnt:輪廓;hull:返回的凸包的角點座標;reuturnPoints=True:代表返回角點的x/y座標
hull = cv.convexHull(cnt, returnPoints=True)
繪製凸包
import cv2 as cv
import numpy as np
# 凸包
# 1.先找到輪廓
img = cv.imread('convex.jpg', 0)
_, thresh = cv.threshold(img, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
contours, hierarchy = cv.findContours(thresh, 3, 2)
cnt = contours[0]
# 2.尋找凸包,得到凸包的角點
hull = cv.convexHull(cnt)
# 3.繪製凸包
image = cv.cvtColor(img, cv.COLOR_GRAY2BGR)
cv.polylines(image, [hull], True, (0, 0, 255), 2)
cv.imshow('convex hull', image)
cv.waitKey(0)
cv.destroyAllWindows()
其中函數 cv.convexHull() 有個可選參數returnPoints,默認是True,代表返回角點的x/y座標;如果爲False的話,表示返回輪廓中是凸包角點的索引,比如說:
print(hull[0]) # [[362 184]](座標)
hull2 = cv.convexHull(cnt, returnPoints=False)
print(hull2[0]) # [510](cnt中的索引)
print(cnt[510]) # [[362 184]]
當使用 cv.convexityDefects() 計算凸包缺陷時,returnPoints需爲False。
判斷輪廓是否是凸形的
print(cv.isContourConvex(hull)) # True