Home > Blockchain >  Removing black background/black stray straight lines from an image in python
Removing black background/black stray straight lines from an image in python

Time:04-13

I am trying read text from enter image description here

import cv2
import numpy as np

img = cv2.imread('text_black_corners.png')


# map the black corners to white   
img2 = img.copy()
img2[np.where((img2 <= [150,150,150]).all(axis=2))] = [255,255,255]

# apply morphology close
kernel = cv2.getStructuringElement(cv2.MORPH_RECT , (3,3))
result = cv2.morphologyEx(img2, cv2.MORPH_CLOSE, kernel)

# write result to disk
cv2.imwrite("text_black_corners_removed.png", result)

# display it
cv2.imshow("img2", img2)
cv2.imshow("result", result)
cv2.waitKey(0)

Result:

enter image description here

CodePudding user response:

As an ad-hoc solution, we may use cv2.floodFill 4 times - one at each corner:

img = cv.imread(file_path, 0)

rows, cols = img.shape

cv.floodFill(img, None, seedPoint=(0, 0), newVal=255, loDiff=1, upDiff=1)  # Fill the top left corner.
cv.floodFill(img, None, seedPoint=(cols-1, 0), newVal=255, loDiff=1, upDiff=1)  # Fill the top right corner.
cv.floodFill(img, None, seedPoint=(0, rows-1), newVal=255, loDiff=1, upDiff=1)  # Fill the bottop left corner.
cv.floodFill(img, None, seedPoint=(cols-1, rows-1), newVal=255, loDiff=1, upDiff=1)  # Fill the bottom right corner.

Result after cv.medianBlur:
enter image description here

  • Related