[Python] Cleaning up scanned book page edges with OpenCV

Discussão em 'Python' iniciado por Stack, Maio 29, 2025.

  1. Stack

    Stack Membro Participativo

    I have several scanned book images that I'm trying to clean up. They've been thresholded and partially cleaned with OpenCV, but there are artifacts around the edges that I've been struggling to remove.

    I tried adding a black border around the edges, then using a flood fill to remove black pixels that were touching the edges. This helps, but it's not perfect. Any ideas how I could improve the process?

    Original images


    [​IMG]

    After border and flood fill


    [​IMG]

    These are the remaining issues I'd like to fix:

    • Image 1: Speckles on the top left and on the right.
    • Image 2: Rings on the left.
    • Image 3: Artifacts on the left.
    • Image 4: "N" in the top right and part of the music in the bottom left were removed.

    Here's my code:

    import os
    import cv2
    import numpy as np

    current_directory = os.path.abspath(os.path.dirname(__file__))
    filenames = ['1.webp', '2.webp', '3.webp', '4.webp']

    for filename in filenames:
    input_path = os.path.join(current_directory, filename)
    output_path = os.path.join(current_directory, filename + '-clean.webp')

    img = cv2.imread(input_path, cv2.IMREAD_GRAYSCALE)

    img = cv2.copyMakeBorder(img, 50, 50, 50, 50, cv2.BORDER_CONSTANT)
    cv2.floodFill(img, None, (0, 0), 255)

    y_nonzero, x_nonzero = np.nonzero(img == 0)
    img = img[np.min(y_nonzero):np.max(y_nonzero), np.min(x_nonzero):np.max(x_nonzero)]

    cv2.imwrite(output_path, img)


    I can provide the full-sized images if it would be helpful, but I'm not sure the best way to include them in the StackOverflow question. Thanks!

    Continue reading...

Compartilhe esta Página