Python去除图像四周黑边:部分图像处理失效问题排查
解决带噪点/浅色白线图像的黑边去除问题
原代码的核心问题是:点状噪点和浅色白线会降低黑边行/列的黑像素占比,导致无法触发black_ratio_thresh阈值,从而无法识别黑边。以下是针对性的改进方案:
改进思路
- 先对图像做降噪处理,消除点状噪点干扰
- 通过二值化强化黑边与非黑边的差异,让黑边区域更易识别
- 可根据图像特性调整阈值参数或滤波方式
改进后的完整代码
import cv2 import numpy as np import os def remove_black_border(image, pixel_thresh=40, black_ratio_thresh=0.10, blur_kernel=(3,3)): # 转为灰度图 gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 高斯模糊降噪,消除点状噪点 blurred = cv2.GaussianBlur(gray, blur_kernel, 0) # 二值化反转:将低于阈值的黑边区域转为白色,其余为黑色,强化黑边特征 _, binary = cv2.threshold(blurred, pixel_thresh, 255, cv2.THRESH_BINARY_INV) h, w = binary.shape def is_row_black(y): # 统计该行黑边像素(二值化后为255)的占比 return np.mean(binary[y, :] == 255) >= black_ratio_thresh def is_col_black(x): return np.mean(binary[:, x] == 255) >= black_ratio_thresh top, bottom = 0, h - 1 left, right = 0, w - 1 # 裁剪顶部黑边 while top <= bottom and is_row_black(top): top += 1 # 裁剪底部黑边 while bottom >= top and is_row_black(bottom): bottom -= 1 # 裁剪左侧黑边 while left <= right and is_col_black(left): left += 1 # 裁剪右侧黑边 while right >= left and is_col_black(right): right -= 1 return image[top:bottom+1, left:right+1] # 路径设置 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"❌ 加载失败: {filename}") continue cropped = remove_black_border(image) output_path = os.path.join(output_folder, filename) cv2.imwrite(output_path, cropped) print(f"✅ 裁剪并保存: {filename}")
额外调整建议
- 如果是椒盐噪点(黑白点状噪点),把高斯模糊换成中值滤波:
blurred = cv2.medianBlur(gray, 3) - 若浅色白线仍干扰,可适当提高
pixel_thresh(如50)或降低black_ratio_thresh(如0.05) - 对于顽固的浅色边框,可尝试先做边缘检测(
cv2.Canny),再通过轮廓提取确定有效区域
内容的提问来源于stack exchange,提问作者Vaidh Velan
相关产品推荐
相关产品推荐

