opencv 多邊形近似物體形狀

前面我們學習過最小外接矩和最小外接圓,那麼可以用一個最小的多邊形包圍物體嗎?當然可以:
其中 cv.approxPolyDP() 的參數1是源圖像的某個輪廓;參數2(epsilon)是一個距離值,表示多邊形的輪廓接近實際輪廓的程度,值越小,越精確;參數3表示是否閉合。

import cv2 as cv
import numpy as np

# 多邊形逼近
# 1.先找到輪廓
img = cv.imread('unregular.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.進行多邊形逼近,得到多邊形的角點
approx1 = cv.approxPolyDP(cnt, 3, True)
approx2 = cv.approxPolyDP(cnt, 15, True)
approx3 = cv.approxPolyDP(cnt, 75, True)

# 3.畫出多邊形
image = cv.cvtColor(img, cv.COLOR_GRAY2BGR)
cv.polylines(image, [approx1], True, (255, 0, 0), 2)
cv.polylines(image, [approx2], True, (0, 255, 0), 2)
cv.polylines(image, [approx3], True, (0, 0, 255), 2)

print(len(approx1),len(approx2),len(approx3))  # 角點的個數
cv.imshow('approxPloyDP', image)
cv.waitKey(0)
cv.destroyAllWindows()

實驗用圖
實驗繪製圖像輸出
實驗控制檯輸出
可以看到,cv.approxPolyDP 函數 參數2(epsilon)越小,得到的多邊形角點越多,對原圖像的多邊形近似效果越好。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章