1. 程式人生 > >cv2 ConvexHull(凸包)

cv2 ConvexHull(凸包)

     通過cv2中函式convexHull能很容易的得到一系列點的凸包,比如由點組成的輪廓,通過convexHull函式,我們就能得到輪廓的凸包。

下面是對地圖進行凸包檢測示例程式碼:

import cv2
import numpy as np
import sys

# 讀取圖片
img = cv2.imread('./sample.jpg', 1)

# 將圖片轉換到灰度空間
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 影象平滑
blur = cv2.blur(gray, (3, 3))

# 影象的二值閾值化
ret, thresh = cv2.threshold(blur, 200, 255, cv2.THRESH_BINARY)

# 輪廓檢測
im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE,
                                           cv2.CHAIN_APPROX_SIMPLE)

# 為凸包點建立陣列
hull =[]

# 計算每個輪廓點
for i in range(len(contours)):
    hull.append(cv2.convexHull(contours[i], False))

# 建立一個空白的黑色圖片
drawing = np.zeros((thresh.shape[0], thresh.shape[1], 3), np.uint8)

# 繪製輪廓和凸包點
for i in range(len(contours)):
    color_contours = (0, 255, 0)  # 輪廓顏色
    color = (255, 255, 255)  # 凸包的顏色
    # 繪製輪廓
    cv2.drawContours(drawing, contours, i, color_contours, 2, 8, hierarchy)
    # 繪製凸包
    cv2.drawContours(drawing, hull, i, color, 2, 8)

cv2.imwrite('result.jpg', drawing)
cv2.imshow("Output", drawing)
cv2.waitKey(0)
cv2.destroyAllWindows()

測試圖片:

測試結果: