如何使用OpenCV修改代码仅去除图像边缘文字、不删除中心内容
图像四周边缘文字去除代码修改方案
原代码问题说明
- 未限制识别区域与图像边缘的距离,中心文字在图像旋转后可能触碰边界,被误判为边缘文字触发裁剪
- 未过滤无效小轮廓,噪声点容易干扰裁剪逻辑
- 单次裁剪未取所有符合条件边缘区域的最小裁剪值,容易出现裁剪错误
核心修改思路
新增边缘范围阈值参数,仅处理距离图像对应边缘*小于阈值(可自行调整,默认50像素)*的文字区域,完全过滤中心区域的文字轮廓,同时优化裁剪逻辑,避免误删中心内容。
修改后完整代码
import cv2 import glob import os import numpy as np def crop_edge_text(img, margin_threshold=50): """ 仅去除图像底部边缘的文字 margin_threshold:仅处理距离底部小于该值的文字区域,避免误删中心内容 """ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1] # 水平膨胀识别横向文字区域 kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (30, 1)) dilate = cv2.dilate(thresh, kernel, iterations=1) cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2] res_img = img.copy() # 记录所有符合条件的边缘文字的上边界y值,取最小的作为裁剪边界 crop_y = img.shape[0] for c in cnts: x, y, w, h = cv2.boundingRect(c) y2 = y + h # 两个判断条件:1. 轮廓触碰底部 2. 轮廓上边缘距离底部小于阈值,属于边缘区域 if y2 >= img.shape[0] and (img.shape[0] - y) < margin_threshold: # 过滤宽度过小的噪声轮廓 if w > 50: crop_y = min(crop_y, y) # 只有当存在符合条件的边缘文字时才裁剪 if crop_y < img.shape[0]: res_img = res_img[0:crop_y-1, :].copy() return res_img def remove_edge_text(image_path, outdir, margin_threshold=50): image = cv2.imread(image_path) # 四边依次裁剪,每次都传入边缘阈值 img1 = crop_edge_text(image, margin_threshold) img2 = crop_edge_text(np.rot90(img1), margin_threshold) img3 = crop_edge_text(np.rot90(img2), margin_threshold) img4 = crop_edge_text(np.rot90(img3), margin_threshold) output_img = np.rot90(img4) cv2.imwrite(os.path.join(outdir, os.path.basename(image_path)), output_img) # 测试调用,可根据自身图像边缘文字的范围调整margin_threshold的数值 if __name__ == '__main__': input_dir = r'/content/Dataset/*' output_dir = r'/content/output' os.makedirs(output_dir, exist_ok=True) for jpgfile in glob.glob(input_dir): print(jpgfile) remove_edge_text(jpgfile, output_dir, margin_threshold=50)
效果验证
输入示例:
输出示例:
参数调整说明
如果边缘文字范围较大,可适当调大margin_threshold参数;如果仍然有误裁情况,可适当调小该参数,也可同步调整轮廓宽度过滤阈值w > 50的数值适配你的场景。
内容的提问来源于stack exchange,提问作者Hamad Younis
相关产品推荐
相关产品推荐

