基于輪廓的圖像分割:
按照輪廓的面積進行排序,取前幾個面積最大的輪廓,畫出并且單獨顯示出來。
import cv2
import numpy
def func(img):
gray = cv2.cvtColor(img,COLOR_BGR2RAGY) #灰階處理
kernel = np.ones((3,3),np.uint8)
# 進行開閉運算,可視情況處理
binary = cv2.morphologyEx(gray, cv2.MORPH_OPEN, kernel)
closing = cv2.morphologyEx(binary,cv2.MORPH_CLOSE,kernel)
# 使用自适應門檻值(局部鄰域塊的高斯權重和)
th3 = cv2.adaptiveThreshold(
gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 17, 7)
contours, hierarchy = cv2.findContours(th3, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 對輪廓進行排序,reverse為True表示降序
contours.sort(key=cnt_arcLength, reverse=True)
contourT = contours[:9]
masks = []
# 分别畫出九個輪廓
for i in range(len(contourT)):
black = np.zeros((img.shape[0], img.shape[1]), dtype=np.uint8)
cv2.drawContours(black, contourT, i, 255, cv2.FILLED)
contour_points = contour_cord(contourT[i])
cv2.imshow('cnts', black)
masks.append(black)
# 對每個輪廓進行和操作
for i in range(len(contourT)):
res = cv2.add(img, np.zeros(np.shape(img), dtype=np.uint8), mask=masks[i])
cv2.imshow('res' + str(i), res)
cv2.drawContours(img, contourT, -1, (255, 0, 0), 2)
cv2.imshow('cnt', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
print(contour_points.tolist())
return contourT, contour_points
if __name__ == '__main__':
inputimg = cv2.imread('men.jpg')
func(inputimg)
結果如下:
剩餘圖檔不一一展示,有興趣的小夥伴可以自行嘗試。