You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何优化低对比度图像预处理方案,提升OCR识别质量并避免信息丢失?

低对比度图像OCR预处理方案优化建议

原始图像

Raw

当前预处理代码

img_yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)
img_yuv[:,:,0] = cv2.equalizeHist(img_yuv[:,:,0])
img_output = cv2.cvtColor(img_yuv, cv2.COLOR_YUV2BGR)
img = img.filter(ImageFilter.GaussianBlur) 
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh, im_bw = cv2.threshold(img, 210, 230, cv2.THRESH_BINARY)
data = Image.fromarray(im_bw)

预处理后结果

Results

优化方案

1. 替换全局直方图均衡化为自适应均衡化

全局均衡化易过度增强噪声,改用CLAHE(自适应直方图均衡化),针对局部区域调整对比度,保留文本细节同时抑制噪声:

clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
img_yuv[:,:,0] = clahe.apply(img_yuv[:,:,0])

2. 调整预处理流程顺序

先转灰度再做高斯模糊,减少计算量且避免色彩通道干扰,同时明确高斯模糊的核参数:

img_gray = cv2.cvtColor(img_output, cv2.COLOR_BGR2GRAY)
img_blur = cv2.GaussianBlur(img_gray, (3,3), 0)

3. 改用自适应阈值分割

固定阈值无法适配光照不均场景,自适应阈值能根据局部区域自动调整阈值,更适配低对比度文本,同时反转阈值让文本为白色(符合OCR输入习惯):

im_bw = cv2.adaptiveThreshold(img_blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)

4. 添加形态学操作优化二值图

二值化后可能存在文本断裂或噪声点,用形态学闭操作填补文本间隙,提升文本完整性:

kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2,2))
im_bw = cv2.morphologyEx(im_bw, cv2.MORPH_CLOSE, kernel)

优化后完整代码

import cv2
from PIL import Image

# 读取图像
img = cv2.imread("your_image_path.jpg")

# YUV色彩空间下执行自适应直方图均衡化
img_yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
img_yuv[:,:,0] = clahe.apply(img_yuv[:,:,0])
img_output = cv2.cvtColor(img_yuv, cv2.COLOR_YUV2BGR)

# 转灰度+高斯模糊降噪
img_gray = cv2.cvtColor(img_output, cv2.COLOR_BGR2GRAY)
img_blur = cv2.GaussianBlur(img_gray, (3,3), 0)

# 自适应阈值二值化
im_bw = cv2.adaptiveThreshold(img_blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)

# 形态学操作优化文本完整性
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2,2))
im_bw = cv2.morphologyEx(im_bw, cv2.MORPH_CLOSE, kernel)

# 转为PIL图像供OCR使用
data = Image.fromarray(im_bw)

内容的提问来源于stack exchange,提问作者user176953

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 01:55:12