import cv2 import numpy as np path = "_holefill.jpg" img = cv2.imread(path) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)#轉換成灰度圖 ret, thresh = cv2.threshold(gray, 50, 250, cv2.THRESH_BINARY_INV)#灰度圖轉換成二值圖像 thresh_not = cv2.bitwise_not(thresh)#二值圖像的補集 kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))#3×3結構元 """ 構建陣列F,並將thresh_not邊界值寫入F """ F = np.zeros(thresh.shape, np.uint8) F[:, 0] = thresh_not[:, 0] F[:, -1] = thresh_not[:, -1] F[0, :] = thresh_not[0, :] F[-1, :] = thresh_not[-1, :] """ 循環迭代,對F進行膨脹操作,結果與thresh_not執行and操作 """ for i in range(200): F_dilation = cv2.dilate(F, kernel, iterations=1) F = cv2.bitwise_and(F_dilation, thresh_not) result = cv2.bitwise_not(F)#對結果執行not #顯示結果 cv2.imshow('p',result) cv2.imshow('r',thresh) cv2.waitKey(0)