有没有更好的方法将文字与背景分开?

Is there a better way to separate the writing from the background?

我正在做一个项目,我应该在一些文件上应用和 OCR。
第一步是对图像进行阈值处理,只让文字(背景变白)。

输入图像示例:出于 GDPR 和隐私原因,此图像来自互联网

这是我的代码:

import cv2
import numpy as np


image = cv2.imread('b.jpg')
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
h = image.shape[0]
w = image.shape[1]
for y in range(0, h):
    for x in range(0, w):
        if image[y, x] >= 120:
            image[y, x] = 255
        else:
            image[y, x] = 0
cv2.imwrite('output.jpg', image)

这是我得到的结果:

当我将 pytesseract 应用于输出图像时,结果并不令人满意(我知道 OCR 并不完美)。虽然我尝试调整阈值(在这段代码中它等于 120),但结果并没有我想要的那么清晰。

有没有什么办法可以设置一个更好的阈值,只保留黑色,其余部分变白?

您可以使用 adaptive thresholding。来自文档:

In this, the algorithm calculate the threshold for a small regions of the image. So we get different thresholds for different regions of the same image and it gives us better results for images with varying illumination.

import numpy as np
import cv2



image = cv2.imread('b.jpg')
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
image = cv2.medianBlur(image ,5)

th1 = cv2.adaptiveThreshold(image,255,cv2.ADAPTIVE_THRESH_MEAN_C,\
            cv2.THRESH_BINARY,11,2)
th2 = cv2.adaptiveThreshold(image,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
            cv2.THRESH_BINARY,11,2)
cv2.imwrite('output1.jpg', th1 )
cv2.imwrite('output2.jpg', th2 )

深入研究 StackOverflow 问题后,我发现 是关于使用 opencv 去除水印的。 我根据自己的需要调整了代码,这就是我得到的:

import numpy as np
import cv2


image = cv2.imread('a.png')
img = image.copy()

alpha =2.75
beta = -160.0

denoised = alpha * img + beta
denoised = np.clip(denoised, 0, 255).astype(np.uint8)

#denoised = cv2.fastNlMeansDenoising(denoised, None, 31, 7, 21)

img = cv2.cvtColor(denoised, cv2.COLOR_BGR2GRAY)

h = img.shape[0]
w = img.shape[1]

for y in range(0, h):
    for x in range(0, w):
        if img[y, x] >= 220:
            img[y, x] = 255
        else:
            img[y, x] = 0

cv2.imwrite('outpu.jpg', img)

这是输出图像:

这段代码的好处在于,它不仅对这张图片给出了很好的结果,而且对我测试过的所有图片都给出了很好的结果。

希望对遇到同样问题的人有所帮助。