pythonopencvphotosedges

Remove blank spaces from scanned photos


I am browsing for days now to find a solution to this problem. No existing solution has worked yet.

Here is my problem : I scan photos, on which there are some blank spaces (that can be anywhere (top, right, left, bottom)). I would like to adjust theses photos by removing the blank spaces.

Here is an example (there's no white square on this original photo, that's just for anonymity) :

Here is the original photo.

Here, I've highlighted what I want to suppress.

And here is what I expect to be the result.

I use OpenCV to do that (Python version) but if you have a solution with another program, no problem!

Has anyone found a solution about how to perform that ?

Thank you. Have a great day !


Solution

  • I used findContours to find a box that you can use to crop your image. Here is the code:

    import cv2
    import numpy as np
    
    
    image = cv2.imread("./FH13g.jpg", cv2.IMREAD_COLOR)
    blurred_image = cv2.GaussianBlur(image, (3,3), 0)
    gray = cv2.cvtColor(blurred_image, cv2.COLOR_BGR2GRAY)
    ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
    mask = 255 - thresh
    
    _, contours, _ = cv2.findContours(mask.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
    
    maxArea = 0
    best = None
    for contour in contours:
      area = cv2.contourArea(contour)
      print (area)
      if area > maxArea :  
        maxArea = area
        best = contour
    
    rect = cv2.minAreaRect(best)
    box = cv2.boxPoints(rect)
    box = np.int0(box)
    cv2.drawContours(image, [box], 0, (0, 0, 255), 3)
    
    while True:
      cv2.imshow("result", image)
      k = cv2.waitKey(30) & 0xff
      if k == 27:
          break