python + opencv實現二值圖像孔洞填充


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)

 

 

 
         
         
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM