logo

20行代码教你如何批量提取图片中文字

作者:有好多问题2025.10.11 17:20浏览量:3

简介:本文通过20行Python代码实现批量图片文字提取,结合Tesseract OCR引擎与Pillow图像处理库,提供从环境配置到代码优化的完整解决方案,助力开发者高效完成文字识别任务。

20行代码实现批量图片文字提取:从原理到实践

在数字化办公场景中,批量提取图片中的文字内容是常见需求。无论是扫描文档处理、票据信息提取,还是社交媒体图片分析,OCR(光学字符识别)技术都发挥着关键作用。本文将通过20行核心代码,结合Tesseract OCR引擎与Python图像处理库,展示如何高效实现批量图片文字提取,并提供完整的实现方案与优化建议。

一、技术选型与原理说明

1.1 OCR技术核心原理

OCR技术通过图像预处理、字符分割、特征提取和模式匹配四个阶段完成文字识别。现代OCR引擎(如Tesseract)采用深度学习模型,对复杂背景、倾斜文字和模糊图像具有更好的适应性。其工作流程包括:

  • 图像二值化:将彩色图像转为黑白,增强文字对比度
  • 降噪处理:消除图像中的噪点干扰
  • 文字区域检测:定位图片中的文字区域
  • 字符识别:通过训练模型匹配字符特征

1.2 技术栈选择

  • Tesseract OCR:Google开源的OCR引擎,支持100+种语言,可通过训练自定义模型
  • Pillow(PIL):Python图像处理库,用于图片格式转换和预处理
  • pytesseract:Tesseract的Python封装接口
  • os模块:处理文件系统操作

二、20行核心代码实现

2.1 环境准备

  1. # 安装依赖库
  2. pip install pillow pytesseract
  3. # 安装Tesseract OCR(Windows需下载安装包,Linux使用apt/yum)

2.2 完整代码实现

  1. import os
  2. from PIL import Image
  3. import pytesseract
  4. def batch_ocr(input_folder, output_file):
  5. """批量提取图片文字并保存到文本文件
  6. Args:
  7. input_folder: 包含图片的文件夹路径
  8. output_file: 输出文本文件路径
  9. """
  10. # 获取文件夹中所有图片文件
  11. image_files = [f for f in os.listdir(input_folder)
  12. if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp'))]
  13. with open(output_file, 'w', encoding='utf-8') as f_out:
  14. for img_file in image_files:
  15. try:
  16. # 构建完整文件路径
  17. img_path = os.path.join(input_folder, img_file)
  18. # 打开图片并转换为灰度图
  19. img = Image.open(img_path).convert('L')
  20. # 使用Tesseract提取文字
  21. text = pytesseract.image_to_string(img, lang='chi_sim+eng')
  22. # 写入文件并添加分隔符
  23. f_out.write(f"=== {img_file} ===\n")
  24. f_out.write(text + "\n\n")
  25. except Exception as e:
  26. print(f"处理 {img_file} 时出错: {str(e)}")
  27. # 使用示例
  28. if __name__ == "__main__":
  29. batch_ocr("input_images", "output.txt")

2.3 代码解析

  1. 文件筛选:通过os.listdir获取指定文件夹中所有图片文件
  2. 图像预处理:使用Image.convert('L')将图片转为灰度图,提升识别率
  3. 多语言支持lang='chi_sim+eng'参数同时支持简体中文和英文识别
  4. 错误处理:try-except块捕获并处理异常,避免单张图片错误导致程序中断
  5. 结果格式化:每张图片的识别结果添加文件名作为分隔符

三、进阶优化与实战技巧

3.1 性能优化方案

  1. 并行处理:使用multiprocessing模块实现多线程处理
    ```python
    from multiprocessing import Pool

def process_image(args):
img_path, lang = args
try:
img = Image.open(img_path).convert(‘L’)
return (img_path, pytesseract.image_to_string(img, lang=lang))
except Exception as e:
return (img_path, f”Error: {str(e)}”)

def parallel_ocr(input_folder, output_file, workers=4):
image_files = [os.path.join(input_folder, f)
for f in os.listdir(input_folder)
if f.lower().endswith((‘.png’, ‘.jpg’))]

  1. with Pool(workers) as pool:
  2. results = pool.map(process_image,
  3. [(img_path, 'chi_sim+eng') for img_path in image_files])
  4. with open(output_file, 'w', encoding='utf-8') as f_out:
  5. for img_path, text in results:
  6. f_out.write(f"=== {os.path.basename(img_path)} ===\n")
  7. f_out.write(text + "\n\n")
  1. 2. **内存管理**:对于大批量图片,采用生成器模式逐个处理
  2. ```python
  3. def image_generator(folder):
  4. for f in os.listdir(folder):
  5. if f.lower().endswith(('.png', '.jpg')):
  6. yield os.path.join(folder, f)

3.2 识别准确率提升技巧

  1. 图像预处理增强
    ```python
    from PIL import ImageFilter

def preprocess_image(img_path):
img = Image.open(img_path)

  1. # 转换为灰度图
  2. img = img.convert('L')
  3. # 二值化处理
  4. img = img.point(lambda x: 0 if x < 140 else 255)
  5. # 降噪处理
  6. img = img.filter(ImageFilter.MedianFilter(size=3))
  7. return img
  1. 2. **自定义训练模型**:
  2. - 下载Tesseract训练工具
  3. - 准备标注好的样本图片
  4. - 生成.box训练文件
  5. - 执行训练命令:
  6. ```bash
  7. tesseract eng.custom.exp0.tif eng.custom.exp0 nobatch box.train

3.3 实际应用场景扩展

  1. PDF文档处理:结合pdf2image库先转换PDF为图片
    ```python
    from pdf2image import convert_from_path

def pdf_to_text(pdf_path, output_file):
images = convert_from_path(pdf_path)
with open(output_file, ‘w’, encoding=’utf-8’) as f_out:
for i, image in enumerate(images):
text = pytesseract.image_to_string(image, lang=’chi_sim’)
f_out.write(f”=== Page {i+1} ===\n”)
f_out.write(text + “\n\n”)

  1. 2. **实时摄像头识别**:使用OpenCV捕获视频
  2. ```python
  3. import cv2
  4. def live_ocr():
  5. cap = cv2.VideoCapture(0)
  6. while True:
  7. ret, frame = cap.read()
  8. if not ret:
  9. break
  10. # 转换为灰度图
  11. gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  12. # 调用Tesseract识别
  13. text = pytesseract.image_to_string(gray, lang='eng')
  14. print(text)
  15. if cv2.waitKey(1) & 0xFF == ord('q'):
  16. break
  17. cap.release()

四、常见问题解决方案

4.1 安装问题处理

  • Windows报错:需设置Tesseract路径

    1. pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
  • Linux依赖缺失

    1. sudo apt install tesseract-ocr libtesseract-dev
    2. # 中文支持包
    3. sudo apt install tesseract-ocr-chi-sim

4.2 识别效果优化

  1. 语言包缺失:从GitHub下载对应语言包
  2. 复杂背景处理
    • 使用边缘检测定位文字区域
    • 应用自适应阈值处理
  3. 倾斜校正
    ```python
    import numpy as np
    import cv2

def correct_skew(img_path):
img = cv2.imread(img_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = cv2.bitwise_not(gray)
coords = np.column_stack(np.where(gray > 0))
angle = cv2.minAreaRect(coords)[-1]
if angle < -45:
angle = -(90 + angle)
else:
angle = -angle
(h, w) = img.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated = cv2.warpAffine(img, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
return rotated
```

五、总结与展望

本文通过20行核心代码展示了批量图片文字提取的实现方法,结合进阶优化技巧和实际应用场景扩展,为开发者提供了完整的解决方案。在实际项目中,建议:

  1. 根据图片质量选择合适的预处理方案
  2. 对于专业领域,训练自定义OCR模型
  3. 大批量处理时采用并行计算提升效率

随着深度学习技术的发展,OCR技术正朝着更高精度、更广语言支持的方向演进。开发者可关注Transformer架构在OCR领域的应用,以及端到端识别模型的发展动态,持续提升文字识别效果。

发表评论

活动