如何用OpenCV Python去除X光图像的白色边框
基于OpenCV/Numpy自动去除X光图像白色边框的实现方案
完全可行,用OpenCV结合Numpy就能批量处理这类带白色边框的X光图像,不管是全环绕的细边框还是侧边局部的白色条带都能搞定,下面给你两种实现思路和具体代码:
方案一:直接裁剪去除白色边框
核心思路是定位出图像主体的边界,直接把边框部分裁掉:
import cv2 import numpy as np def crop_white_borders(img_path, threshold=240): # 读取图像并转为灰度图 img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE) # 二值化:将接近白色的区域(亮度≥threshold)标记为背景 _, binary = cv2.threshold(img, threshold, 255, cv2.THRESH_BINARY) # 定位所有非白色背景的像素坐标 coords = np.column_stack(np.where(binary < 255)) # 计算图像主体的上下左右边界 y_min, x_min = coords.min(axis=0) y_max, x_max = coords.max(axis=0) # 裁剪出主体区域 cropped_img = img[y_min:y_max+1, x_min:x_max+1] return cropped_img
如果图像存在零星白色噪声点,可在二值化后添加形态学腐蚀过滤干扰:
# 在二值化步骤后插入 kernel = np.ones((3,3), np.uint8) binary = cv2.erode(binary, kernel, iterations=1)
方案二:将白色边框替换为黑/灰色
如果不想改变图像尺寸,仅把白色边框替换为深色:
def replace_white_borders(img_path, target_color=0, threshold=240): img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE) _, binary = cv2.threshold(img, threshold, 255, cv2.THRESH_BINARY) # 生成白色边框区域的掩码 mask = binary == 255 # 将边框区域替换为目标颜色 img[mask] = target_color return img
target_color设为0是黑色,设为127是中灰色,可根据需求调整。
批量处理示例
处理文件夹内所有X光图像的代码:
import os input_dir = "你的X光图像文件夹路径" output_dir = "处理后图像保存路径" os.makedirs(output_dir, exist_ok=True) for filename in os.listdir(input_dir): if filename.endswith(('.png', '.jpg', '.jpeg')): img_path = os.path.join(input_dir, filename) # 选择裁剪或替换方案 processed_img = crop_white_borders(img_path) # processed_img = replace_white_borders(img_path, target_color=0) cv2.imwrite(os.path.join(output_dir, filename), processed_img)
注意事项
- 阈值
threshold可根据图像实际情况微调:若白色边框不是纯白,可适当降低数值; - 两种方案对侧边局部白色条带的图像同样适用,不会误处理图像主体。
内容的提问来源于stack exchange,提问作者Bathtub
相关产品推荐
相关产品推荐

