这里有两种方法:
方法#1:轮廓过滤
我们将图像转换为灰度(二值图像的 Otsu 阈值),然后查找轮廓并使用最小阈值区域进行过滤。我们通过在轮廓上绘制填充来去除黑点,以有效擦除黑点
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()
Run Code Online (Sandbox Code Playgroud)
方法#2:形态运算
同样,我们先转换为灰度,然后转换为大津阈值。从这里我们创建一个内核并执行 morph open
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()
Run Code Online (Sandbox Code Playgroud)