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

如何用Python提取图片表格内容生成CSV?识别失败问题排查

问题描述

需要提取图片中表格的文字与数字,生成与表格结构一致的CSV文件。

当前使用的代码
import cv2
import os,argparse
import pytesseract
from PIL import Image

pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'

ap=argparse.ArgumentParser()
ap.add_argument("-i","--image",
                required=True,
                help="Path to the image folder")
ap.add_argument("-p","--pre_processor",
                default="thresh", 
                help="the preprocessor usage")
args=vars(ap.parse_args())
 
images=cv2.imread(args["image"])
 
#convert to grayscale image
gray=cv2.cvtColor(images, cv2.COLOR_BGR2GRAY)
 
#checking whether thresh or blur
if args["pre_processor"]=="thresh":
    cv2.threshold(gray, 0,255,cv2.THRESH_BINARY| cv2.THRESH_OTSU)[1]
if args["pre_processor"]=="blur":
    cv2.medianBlur(gray, 3)
     

filename = "{}.bmp".format(os.getpid())
cv2.imwrite(filename, gray)
text = pytesseract.image_to_string(Image.open(filename), config='--psm 7')
os.remove(filename)
print(text)
 
#cv2.imshow("Image Input", images)
#cv2.imshow("Output In Grayscale", gray)
cv2.waitKey(0)
处理结果
  • 预处理后的图片:图像仍存在模糊,表格线条和文字边缘不够清晰
  • 识别输出:
    : RF
    
疑问

是否存在明显的代码错误?是否因图片模糊导致识别困难?

分析与解决

1. 代码中的明显错误

  • 预处理操作未生效:cv2.threshold和cv2.medianBlur的处理结果没有赋值回gray变量,导致后续保存的还是原始灰度图,预处理完全没起作用。
    修正代码:
    if args["pre_processor"]=="thresh":
        gray = cv2.threshold(gray, 0,255,cv2.THRESH_BINARY| cv2.THRESH_OTSU)[1]
    if args["pre_processor"]=="blur":
        gray = cv2.medianBlur(gray, 3)
    
  • PSM参数选择错误:--psm 7的作用是将图像视为单行文本,但目标是表格,该参数会限制Tesseract的识别范围,导致大部分表格内容被忽略。建议更换为更适合的模式,比如--psm 6(将图像视为单一均匀文本块)或--psm 11(自动检测文本区域)。

2. 图片模糊的影响

图片模糊确实会严重降低识别准确率,尤其是表格的细线条和小字号文字。可以尝试以下优化预处理步骤:

  • 使用自适应阈值替代全局阈值:cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2),能更好应对局部亮度不均的情况
  • 加入形态学操作:用cv2.morphologyEx进行膨胀或腐蚀,增强文字和表格线条的清晰度
  • 放大图片:对低分辨率图片进行插值放大,比如cv2.resize(gray, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC),提升文字边缘的辨识度

优化后的示例代码

import cv2
import os,argparse
import pytesseract
from PIL import Image

pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'

ap=argparse.ArgumentParser()
ap.add_argument("-i","--image", required=True, help="Path to the image")
args=vars(ap.parse_args())
 
image = cv2.imread(args["image"])
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# 自适应阈值处理
gray = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)
# 形态学操作增强线条
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2,2))
gray = cv2.morphologyEx(gray, cv2.MORPH_CLOSE, kernel)

filename = "{}.bmp".format(os.getpid())
cv2.imwrite(filename, gray)
# 使用PSM 6,同时指定字符集提升准确率
text = pytesseract.image_to_string(Image.open(filename), config='--psm 6 -c tessedit_char_whitelist=0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ:/ ')
os.remove(filename)
print(text)

cv2.waitKey(0)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 02:17:17