使用opencv仅删除图像中的黑点

时间:2019-10-31 05:04:12

标签: image opencv image-processing filtering

我发布信息是为了了解这可能仅去除图像中的黑点。

Image

1 个答案:

答案 0 :(得分:3)

这里有两种方法:

方法1:轮廓过滤

我们将图像转换为灰度,即大津的二进制图像阈值,然后找到轮廓并使用最小阈值区域进行过滤。我们通过填充轮廓来消除黑点,以有效消除黑点

enter image description here

import cv2

image = cv2.imread('1.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    if cv2.contourArea(c) < 10:
        cv2.drawContours(thresh, [c], -1, (0,0,0), -1)

result = 255 - thresh
cv2.imshow('result', result)
cv2.waitKey()

方法2:形态学操作

类似地,我们转换为灰度,然后转换为大津的阈值。从这里我们创建一个内核并执行morph open

enter image description here

import cv2

image = cv2.imread('1.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
opening = 255 - cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=1)

cv2.imshow('opening', opening)
cv2.waitKey()