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, :] = black_ratio_thresh
def is_col_black(x):
return np.mean(gray[:, x] = black_ratio_thresh
# Start from full image
top, bottom = 0, h - 1
left, right = 0, w - 1
# Remove top border
while top = top and is_row_black(bottom):
bottom -= 1
# Remove left border
while left = 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"
continue
cropped = remove_black_border(image)
output_path = os.path.join(output_folder, filename)
cv2.imwrite(output_path, cropped)
print(f"
Подробнее здесь: https://stackoverflow.com/questions/797 ... ing-python