参考:
https://stackoverflow.com/questions/1716274/fill-the-holes-in-opencv
# -*- coding: UTF-8 -*-
import cv2
import numpy as np
img=cv2.imread("j.png",0)
hole=img.copy()
cv2.floodFill(hole,None,(0,0),255) # 找到洞孔
hole=cv2.bitwise_not(hole)
# filledEdgesOut = (img | hole)
# or
filledEdgesOut=cv2.bitwise_or(img,hole)
# or
filledEdgesOut=cv2.add(img,hole)
# cv2.imshow("img",img)
# cv2.imshow("hole",hole)
cv2.imshow("filledEdgesOut",filledEdgesOut)
cv2.waitKey(0)
cv2.destroyAllWindows()
# -*- coding: UTF-8 -*-
import cv2
import numpy as np
img=cv2.imread("j.png",0)
def cvFillHoles(img):
"""
# assume input is uint8 B & W(0 or 1)
# this function imitates imfill(image, 'hole')
"""
holes = img.copy()
cv2.floodFill(holes,None, (0,0), 1) # 找到洞孔
for i in range(img.shape[0]):
for j in range(img.shape[1]):
if holes[i,j]==0:
img[i,j]=255
return img
filledEdgesOut=cvFillHoles(img)
cv2.imshow("filledEdgesOut",filledEdgesOut)
cv2.waitKey(0)
cv2.destroyAllWindows()
参考:https://stackoverflow.com/questions/10316057/filling-holes-inside-a-binary-object
# -*- coding: UTF-8 -*-
import cv2
import numpy as np
img=cv2.imread("123.png",0)
gray=img.copy()
# _,gray=cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY_INV)
des=cv2.bitwise_not(gray)
image, contours, hierarchy = cv2.findContours(des,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE)
des=cv2.drawContours(des,contours,-1,255,-1) # -1 表示绘制所有轮廓 最后一个-1 表填充
# 或
# for cnt in contours:
# cv2.drawContours(des,[cnt],0,255,-1)
gray = cv2.bitwise_not(des)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))
res = cv2.morphologyEx(gray,cv2.MORPH_OPEN,kernel)
cv2.imshow("res",res)
cv2.waitKey(0)
cv2.destroyAllWindows()
或
# -*- coding: UTF-8 -*-
import cv2
import numpy as np
img=cv2.imread("123.png",0)
gray=img.copy()
_,des=cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY_INV)
# des=cv2.bitwise_not(gray)
image, contours, hierarchy = cv2.findContours(des,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE)
gray = cv2.bitwise_not(image)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))
res = cv2.morphologyEx(gray,cv2.MORPH_OPEN,kernel)
cv2.imshow("res",res)
cv2.waitKey(0)
cv2.destroyAllWindows()
或
# -*- coding: UTF-8 -*-
import cv2
import numpy as np
img=cv2.imread("123.png",0)
gray=img.copy()
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))
res = cv2.morphologyEx(gray,cv2.MORPH_OPEN,kernel)
cv2.imshow("res",res)
cv2.waitKey(0)
cv2.destroyAllWindows()