您可以使用简单的轮廓区域过滤来去除噪声。这个想法是找到轮廓,使用cv2.contourArea() 过滤,然后将有效轮廓绘制到空白蒙版上。为了在没有噪声的情况下重建图像,我们将输入图像与掩码进行逐位运算以得到我们的结果。
要移除的噪音以绿色突出显示
结果
代码
import cv2
import numpy as np
# Load image, create blank mask, grayscale, Otsu's threshold
image = cv2.imread('1.png')
mask = np.zeros(image.shape, dtype=np.uint8)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
# Find contours and filter using contour area
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:
area = cv2.contourArea(c)
if area > 250:
cv2.drawContours(mask, [c], -1, (255,255,255), -1)
# Bitwise and to reconstruct image
result = cv2.bitwise_and(image, mask)
cv2.imshow('mask', mask)
cv2.imshow('result', result)
cv2.waitKey()
注意:如果您知道文本将是黄色的,另一种方法是使用颜色阈值来隔离文本。您可以使用this HSV color thresholder script 来确定下限/上限