【发布时间】:2021-02-28 10:13:11
【问题描述】:
这是我的代码,我正在尝试从二进制图像中删除掩码(噪声)。我得到的是噪音周围留下的白线。我知道该噪声周围有一个轮廓,会在结果中产生最终的白线。有什么帮助吗?
原图
面具和结果
代码
import numpy as np
import cv2
from skimage import util
img = cv2.imread('11_otsu.png')
imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgray, 127, 255, 0, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
#cv2.drawContours(img, contours, -1, (0,255,0), 2)
# create an empty mask
mask = np.zeros(img.shape[:2], dtype=np.uint8)
# loop through the contours
for i, cnt in enumerate(contours):
# if the contour has no other contours inside of it
if hierarchy[0][i][2] == -1:
# if the size of the contour is greater than a threshold
if cv2.contourArea(cnt) <70:
cv2.drawContours(mask, [cnt], 0, (255), -1)
# display result
cv2.imshow("Mask", mask)
cv2.imshow("Img", img)
image = cv2.bitwise_not(img, img, mask=mask)
cv2.imshow("Mask", mask)
cv2.imshow("After", image)
cv2.waitKey()
cv2.destroyAllWindows()
【问题讨论】:
-
只需在命令附近添加形态来填充白色区域内的黑洞。然后只得到外部轮廓。见docs.opencv.org/4.1.1/d4/d86/…
标签: python python-3.x opencv image-processing cv2