基于轮廓的图像分割:
按照轮廓的面积进行排序,取前几个面积最大的轮廓,画出并且单独显示出来。
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)
结果如下:
剩余图片不一一展示,有兴趣的小伙伴可以自行尝试。