使用cv2与pytesseract进行OCR图像文本提取结果不准确的问题
OCR文本提取不一致问题排查
问题描述
我正在使用cv2和pytesseract库提取image3_3.png中的文本,Python实现代码如下:
def threshold_image(img_src): """Grayscale image and apply Otsu's threshold""" # Grayscale img_gray = cv2.cvtColor(img_src, cv2.COLOR_BGR2GRAY) # Binarisation and Otsu's threshold img_thresh = cv2.threshold(img_gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1] return img_thresh img = np.array(Image.open('image3_3.png')) # Apply dilation and erosion to remove some noise kernel = np.ones((1, 1), np.uint8) img = cv2.dilate(img, kernel, iterations=1) img = cv2.erode(img, kernel, iterations=1) # normalise the image norm_img = np.zeros((img.shape[0], img.shape[1])) img = cv2.normalize(img, norm_img, 0, 255, cv2.NORM_MINMAX) # Apply blur to smooth out the edges img = cv2.GaussianBlur(img, (5, 5), 0) string_ocr = pytesseract.image_to_string(threshold_image(img), lang = 'eng', config = '--psm 6') print(string_ocr)
执行代码后得到的OCR结果:
Image A3. This is image A3 with more texts. ISAS Visual Analytics INow everyone can easily discover and share powerful Nsights that inspire action
可以看到结果中存在字符识别错误(如INow应为Now,Nsights应为Insights),无法提取到与图像完全一致的文本,求解决方法。
问题原因与解决方法
1. 图像预处理步骤存在冗余与不当操作
- 无效形态学操作:使用
(1,1)的核执行膨胀和腐蚀,对图像像素没有任何修改,属于冗余操作。 - 过度高斯模糊:
(5,5)的高斯模糊核会过度平滑文本边缘,导致字符细节丢失,直接影响Tesseract的字符识别精度。 - 预处理顺序不合理:先模糊再做阈值处理,会进一步弱化字符特征,增加识别难度。
2. Tesseract配置参数适配性不足
当前使用--psm 6(假设图像为单一均匀文本块),若图像中文本存在字号差异、复杂排版,该参数无法适配场景,导致识别偏差。
改进后的代码示例
import cv2 import numpy as np from PIL import Image import pytesseract def preprocess_image(img_src): # 转换为灰度图 img_gray = cv2.cvtColor(img_src, cv2.COLOR_BGR2GRAY) # 自适应阈值处理,适配光照不均场景 img_thresh = cv2.adaptiveThreshold( img_gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2 ) # 用2x2核执行开运算,去除小噪声点 kernel = np.ones((2,2), np.uint8) img_clean = cv2.morphologyEx(img_thresh, cv2.MORPH_OPEN, kernel, iterations=1) return img_clean # 读取图像 img = np.array(Image.open('image3_3.png')) # 执行优化后的预处理 processed_img = preprocess_image(img) # 调整Tesseract参数:使用自动分割模式,添加字符白名单减少误判 string_ocr = pytesseract.image_to_string( processed_img, lang='eng', config='--psm 3 -c tessedit_char_whitelist="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,!? "' ) print(string_ocr)
额外优化建议
- 图像矫正:如果原图像存在倾斜、透视变形,先通过霍夫变换、透视变换等操作矫正图像。
- 自定义字库训练:若图像包含特殊字体或字符,可针对该字体训练Tesseract字库,提升识别准确率。
- 阈值方法对比:尝试Otsu阈值、自适应阈值、全局阈值等不同方式,选择最适配当前图像的阈值处理方案。
内容的提问来源于stack exchange,提问作者Rhombus
相关产品推荐
相关产品推荐

