OpenCV 将所有文本处理为白底黑字(分割)

OpenCV process all text to be black on white (segmentation)

是否有可能以某种方式使文档中的所有文本在阈值处理后都是白底黑字。我一直在网上寻找很多,但我一直无法找到解决方案。我当前的阈值图像是:https://i.ibb.co/Rpqcp7v/thresh.jpg

文档需要由 OCR 读取,为此我需要反转当前黑底白字的区域。我该怎么做呢?我当前的代码:

# thresholding
def thresholding(image):
    # thresholds the image into a binary image (black and white)
    return cv2.threshold(image, 120, 255, cv2.THRESH_BINARY)[1]

使用中值滤波器估计主色(背景)。

然后从中减去图像...您将得到黑底白字。我正在使用 absolute 差异。反转为白底黑字。

im = cv.imread("thresh.jpg", cv.IMREAD_GRAYSCALE)
im = cv.pyrDown(cv.pyrDown(im)) # picture too large for stack overflow
bg = cv.medianBlur(im, 51) # suitably large kernel to cover all text
out = 255 - cv.absdiff(bg, im)