[Python] Removing Sourrounding black borders from image using python

Discussão em 'Python' iniciado por Stack, Julho 14, 2025.

  1. Stack

    Stack Membro Participativo

    Im using the below code to remove black borders left,right,top, bottom from an image. but the problem is its not removing borders left/right/top/bottom from some images. i checked the images it has some light white lines and dots. please help.

    import cv2
    import numpy as np
    import os

    def remove_black_border(image, pixel_thresh=40, black_ratio_thresh=0.10):
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    h, w = gray.shape

    def is_row_black(y):
    return np.mean(gray[y, :] <= pixel_thresh) >= black_ratio_thresh

    def is_col_black(x):
    return np.mean(gray[:, x] <= pixel_thresh) >= black_ratio_thresh

    # Start from full image
    top, bottom = 0, h - 1
    left, right = 0, w - 1

    # Remove top border
    while top <= bottom and is_row_black(top):
    top += 1

    # Remove bottom border
    while bottom >= top and is_row_black(bottom):
    bottom -= 1

    # Remove left border
    while left <= right and is_col_black(left):
    left += 1

    # Remove right border
    while right >= left and is_col_black(right):
    right -= 1

    # Return cropped image
    return image[top:bottom+1, left:right+1]

    # Set paths
    input_folder = "input/RB Images"
    output_folder = "output/RB Images"
    os.makedirs(output_folder, exist_ok=True)

    for filename in os.listdir(input_folder):
    if filename.lower().endswith((".jpg", ".jpeg", ".png", ".tif", ".tiff")):
    input_path = os.path.join(input_folder, filename)
    image = cv2.imread(input_path)

    if image is None:
    print(f"❌ Failed to load: {filename}")
    continue

    cropped = remove_black_border(image)
    output_path = os.path.join(output_folder, filename)
    cv2.imwrite(output_path, cropped)
    print(f"✅ Cropped and saved: {filename}")

    Continue reading...

Compartilhe esta Página