这是一个完全编码的 Python 解决方案,基于 @eldesgraciado 提供的方向。
此代码假定您已经在使用正确二值化的黑白图像(例如,在灰度转换、黑帽变形和 Otsu 的阈值处理之后) - OpenCV 文档建议在应用形态学时使用具有白色前景的二值化图像操作和类似的东西。
num_comps, labeled_pixels, comp_stats, comp_centroids = \
cv2.connectedComponentsWithStats(thresh_image, connectivity=4)
min_comp_area = 10 # pixels
# get the indices/labels of the remaining components based on the area stat
# (skip the background component at index 0)
remaining_comp_labels = [i for i in range(1, num_comps) if comp_stats[i][4] >= min_comp_area]
# filter the labeled pixels based on the remaining labels,
# assign pixel intensity to 255 (uint8) for the remaining pixels
clean_img = np.where(np.isin(labeled_pixels,remaining_comp_labels)==True,255,0).astype('uint8')
此解决方案的优势在于,它可以让您过滤掉噪音,而不会对可能已经被破坏的字符产生负面影响。
我使用具有不良影响的脏扫描,如合并字符和字符腐蚀,我发现没有免费午餐的艰难方法 - 即使是看似无害的 3x3 内核打开操作和一次迭代也会导致一些字符退化(尽管对于消除字符周围的噪音非常有效)。
因此,如果字符质量允许,对整个图像进行钝化清理操作(例如模糊、打开、关闭)是可以的,但如果不是 - 这应该首先完成。
附:还有一件事 - 在处理文本图像时,您不应该使用像 JPEG 这样的有损格式,而是使用像 PNG 这样的无损格式。