Skip to content Skip to sidebar Skip to footer

Remove Top Section Of Image Above Border Line To Detect Text Document

Using OpenCV (python) I am trying to remove the section of image which is above the border line (white area in this sample image where ORIGINAL is writtn) in the image shown below

Solution 1:

Instead of trying to find horizontal/vertical lines to detect the text document, a simple contour filtering approach should work here. The idea is to threshold the image to obtain a binary image then find contours and sort using contour area. The largest contour should be the text document. We can then apply a four point perspective transform to obtain a birds eye view of the image. Here's the results:

Input image:

Output:

Notice how the output image only has the desired text document and is aligned without a skewed angle.

Code

from imutils.perspective import four_point_transform
import cv2
import numpy

# Load image, grayscale, Gaussian blur, Otsu's threshold
image = cv2.imread("1.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3,3), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Find contours and sort for largest contour
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] iflen(cnts) == 2else cnts[1]
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
displayCnt = Nonefor c in cnts:
    # Perform contour approximation
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.02 * peri, True)
    iflen(approx) == 4:
        displayCnt = approx
        break# Obtain birds' eye view of image
warped = four_point_transform(image, displayCnt.reshape(4, 2))

cv2.imshow("thresh", thresh)
cv2.imshow("warped", warped)
cv2.imshow("image", image)
cv2.waitKey()

Post a Comment for "Remove Top Section Of Image Above Border Line To Detect Text Document"