[Python] How to crop image in OpenCV to keep only the white page with text, excluding darker...

Discussão em 'Python' iniciado por Stack, Agosto 23, 2025.

  1. Stack

    Stack Membro Participativo

    I have scanned pages where the page is surrounded by gray/dark borders. I want to crop the image so that only the white page with the text remains — without any parts of the darker borders.

    Most of the solutions I found use contour detection, which gives me the outer bounding box around the page. But this still includes the dark borders.

    Example (illustration):

    Original scan: white page + gray border

    Current result: bounding box includes both page and border

    [​IMG]

    Desired result: crop only the inner white page (with text), no gray border

    [​IMG]

    What I tried so far:

    import cv2

    img = cv2.imread("scan.png", cv2.IMREAD_GRAYSCALE)

    # Threshold

    _, th = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

    # Find contours

    contours, _ = cv2.findContours(th, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # Bounding box

    x, y, w, h = cv2.boundingRect(max(contours, key=cv2.contourArea))

    cropped = img[y:y+h, x:x+w]


    This works for finding the outer box, but it still contains the gray border.

    Question:

    How can I detect and crop only the inner white page with text, excluding the surrounding dark/gray border, using OpenCV?

    Continue reading...

Compartilhe esta Página