Search code examples
pythonopencvpython-tesseract

How to change the background to white using OpenCV


Image

image

I want to change the background of the image to white for OCR.

Result

result

image = cv2.imread('./screenshot_2.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
threshold_value = 150
_, image = cv2.threshold(gray, threshold_value, 255, cv2.THRESH_BINARY_INV)
contours, _ = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
largest_contour = max(contours, key=cv2.contourArea)
height, width = image.shape
image = np.ones((height, width), np.uint8) * 255 
cv2.drawContours(image, [largest_contour], -1, 0, -1)

Expecting

expecting

I want the image to change like this.


Solution

  • You can do that in Python/OpenCV by flood filling with white.

    Input:

    enter image description here

    import cv2
    import numpy as np
    
    # read the input as grayscale
    img = cv2.imread('tentagruel.png', cv2.IMREAD_GRAYSCALE)
    hh, ww = img.shape[:2]
    
    # add black border to ensure black all around
    img2 = cv2.copyMakeBorder(img, 5, 5, 5, 5, borderType=cv2.BORDER_CONSTANT, value=(0,0,0))
    hh2 = hh+10
    ww2 = ww+10 
    
    # create mask image for floodfill
    # create zeros mask 2 pixels larger in each dimension
    mask = np.zeros([hh2 + 2, ww2 + 2], np.uint8)
    
    # apply floodfill from top-left corner
    result = img2.copy()
    cv2.floodFill(result, mask, (0,0), 255, 0, 200, flags=8)[1]
    
    # save the result
    cv2.imwrite('tentagruel_proc.png', result)
    
    # show result
    cv2.imshow('result', result)
    cv2.waitKey(0)
    

    Result:

    enter image description here