基于二值图转换
1 import cv2 2 import numpy as np 3 4 def find_max_region(mask_sel): 5 6 contours, hierarchy = cv2.findContours(mask_sel, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) 7 8 # 找到最大区域并填充 9 area = [] 10 11 for j in range(len(contours)): 12 area.append(cv2.contourArea(contours[j])) 13 14 max_idx = np.argmax(area) 15 16 max_area = cv2.contourArea(contours[max_idx]) 17 18 for k in range(len(contours)): 19 20 if k != max_idx: 21 cv2.fillPoly(mask_sel, [contours[k]], 0) 22 23 24 25 return mask_sel 26 27 if __name__ == '__main__': 28 img_path = "多个连通域待查.jpg" 29 img = cv2.imread(img_path) 30 img2 =cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #THRESH_BINARY #COLOR_BGR2GRAY 31 cv2.imshow('zhang',img2) 32 img3=find_max_region(img2) 33 cv2.imwrite("最大轮廓.png", img3)