Python实现图片格式转换与OCR文字识别全攻略

Python实现图片格式转换与OCR文字识别全攻略

一、引言:图片处理与文字识别的双重需求

在数字化办公场景中,图片格式转换与文字识别(OCR)是两项高频需求。例如,将扫描的合同PDF转为PNG以便编辑,或从产品图片中提取规格参数。传统方法需依赖多个工具分步操作,而Python可通过单一脚本实现”格式转换+文字识别”的完整流程。本文将基于Pillow库实现图片格式转换,结合Tesseract OCR引擎完成文字识别,并提供优化方案。

二、图片格式转换:Pillow库的深度应用

2.1 Pillow库基础功能

Pillow(PIL)是Python最强大的图像处理库之一,支持JPEG、PNG、BMP、TIFF等20余种格式转换。其核心操作流程为:

  1. from PIL import Image
  2. def convert_image_format(input_path, output_path, target_format):
  3. """
  4. 图片格式转换函数
  5. :param input_path: 输入文件路径
  6. :param output_path: 输出文件路径
  7. :param target_format: 目标格式(如'JPEG'、'PNG')
  8. """
  9. try:
  10. img = Image.open(input_path)
  11. # 确保扩展名与格式一致
  12. output_path = output_path.rsplit('.', 1)[0] + '.' + target_format.lower()
  13. img.save(output_path, format=target_format)
  14. print(f"转换成功:{input_path} → {output_path}")
  15. except Exception as e:
  16. print(f"转换失败:{str(e)}")
  17. # 示例:将PNG转为JPEG
  18. convert_image_format('input.png', 'output.jpg', 'JPEG')

2.2 高级转换技巧

  • 批量处理:通过os.listdir()遍历文件夹实现批量转换
    ```python
    import os

def batch_convert(input_dir, output_dir, target_format):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for filename in os.listdir(input_dir):
if filename.lower().endswith((‘.png’, ‘.jpg’, ‘.bmp’)):
input_path = os.path.join(input_dir, filename)
output_path = os.path.join(output_dir,
os.path.splitext(filename)[0] + f’.{target_format.lower()}’)
convert_image_format(input_path, output_path, target_format)

  1. - **质量参数控制**:JPEG格式可通过`quality`参数(1-100)调整压缩率
  2. ```python
  3. img.save('output.jpg', format='JPEG', quality=85) # 推荐85%质量平衡体积与清晰度
  • 透明通道处理:PNG转JPEG时需处理alpha通道
    1. def png_to_jpeg(input_path, output_path):
    2. img = Image.open(input_path)
    3. if img.mode in ('RGBA', 'LA'):
    4. background = Image.new('RGB', img.size, (255, 255, 255)) # 白色背景
    5. background.paste(img, mask=img.split()[-1])
    6. background.save(output_path, 'JPEG', quality=90)
    7. else:
    8. img.save(output_path, 'JPEG', quality=90)

三、OCR文字识别:Tesseract的集成与优化

3.1 Tesseract OCR基础配置

需先安装Tesseract引擎(Windows/Mac通过官网安装包,Linux用apt install tesseract-ocr)和Python封装库:

  1. pip install pytesseract pillow

基础识别代码:

  1. import pytesseract
  2. from PIL import Image
  3. def ocr_recognize(image_path, lang='chi_sim+eng'):
  4. """
  5. OCR文字识别
  6. :param image_path: 图片路径
  7. :param lang: 语言包(中文简体+英文)
  8. :return: 识别文本
  9. """
  10. try:
  11. img = Image.open(image_path)
  12. text = pytesseract.image_to_string(img, lang=lang)
  13. return text
  14. except Exception as e:
  15. print(f"OCR识别失败:{str(e)}")
  16. return None
  17. # 示例
  18. print(ocr_recognize('converted.jpg'))

3.2 识别准确率优化方案

  1. 图像预处理

    • 二值化处理:
      1. def preprocess_image(image_path):
      2. img = Image.open(image_path).convert('L') # 转为灰度图
      3. threshold = 140 # 阈值需根据图片调整
      4. table = []
      5. for i in range(256):
      6. if i < threshold:
      7. table.append(0)
      8. else:
      9. table.append(1)
      10. return img.point(table, '1') # 二值化
  2. 区域识别

    1. def ocr_with_area(image_path, box_coords, lang='eng'):
    2. """
    3. 指定区域识别
    4. :param box_coords: (x1,y1,x2,y2) 左上右下坐标
    5. """
    6. img = Image.open(image_path)
    7. area = img.crop(box_coords)
    8. return pytesseract.image_to_string(area, lang=lang)
  3. 多语言支持

    • 下载额外语言包(如tesseract-ocr-chi-sim中文包)
    • 配置pytesseract.pytesseract.tesseract_cmd指定引擎路径(Windows必需)

四、完整流程实现:转换+识别一体化

  1. def image_process_pipeline(input_path, output_format='JPEG', lang='chi_sim+eng'):
  2. """
  3. 完整处理流程:
  4. 1. 格式转换
  5. 2. 预处理优化
  6. 3. OCR识别
  7. """
  8. # 1. 格式转换(示例转为JPEG)
  9. temp_path = 'temp_processed.jpg'
  10. convert_image_format(input_path, temp_path, 'JPEG')
  11. # 2. 图像预处理
  12. processed_img = preprocess_image(temp_path)
  13. processed_img.save('preprocessed.jpg')
  14. # 3. OCR识别
  15. text = ocr_recognize('preprocessed.jpg', lang=lang)
  16. # 清理临时文件
  17. import os
  18. os.remove(temp_path)
  19. return text
  20. # 使用示例
  21. result = image_process_pipeline('input_document.png')
  22. print("识别结果:\n", result)

五、性能优化与工程化建议

  1. 多线程处理

    1. from concurrent.futures import ThreadPoolExecutor
    2. def parallel_process(image_paths, max_workers=4):
    3. with ThreadPoolExecutor(max_workers=max_workers) as executor:
    4. futures = [executor.submit(image_process_pipeline, path) for path in image_paths]
    5. return [future.result() for future in futures]
  2. 错误处理机制

    • 添加重试逻辑(网络图片下载场景)
    • 记录失败日志(含图片路径、错误类型)
  3. 输出格式化

    1. def format_ocr_result(text):
    2. """将OCR原始输出转为结构化数据"""
    3. import re
    4. paragraphs = [p.strip() for p in text.split('\n') if p.strip()]
    5. return {
    6. 'paragraph_count': len(paragraphs),
    7. 'text_content': '\n'.join(paragraphs),
    8. 'word_count': len(re.findall(r'\w+', text))
    9. }

六、实际应用场景与扩展

  1. 自动化文档处理

    • 扫描合同→转为PDF→提取关键条款
    • 发票识别→结构化数据存储
  2. Web服务集成

    1. from flask import Flask, request, jsonify
    2. app = Flask(__name__)
    3. @app.route('/ocr', methods=['POST'])
    4. def ocr_api():
    5. if 'file' not in request.files:
    6. return jsonify({'error': 'No file uploaded'}), 400
    7. file = request.files['file']
    8. file.save('temp.jpg')
    9. text = image_process_pipeline('temp.jpg')
    10. return jsonify({'text': text})
    11. if __name__ == '__main__':
    12. app.run(port=5000)
  3. 移动端适配

    • 使用Kivy框架构建跨平台APP
    • 通过REST API连接云端处理

七、常见问题解决方案

  1. Tesseract安装失败

    • Windows用户需将Tesseract添加到PATH环境变量
    • 指定引擎路径:
      1. pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
  2. 中文识别率低

    • 确认已安装中文语言包(chi_sim
    • 增加训练数据(通过jTessBoxEditor工具)
  3. 复杂背景干扰

    • 使用OpenCV进行边缘检测和背景去除
      1. import cv2
      2. def remove_background(image_path):
      3. img = cv2.imread(image_path)
      4. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
      5. _, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY_INV)
      6. kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
      7. dilated = cv2.dilate(thresh, kernel, iterations=2)
      8. contours, _ = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
      9. mask = np.zeros_like(gray)
      10. cv2.drawContours(mask, contours, -1, 255, -1)
      11. result = cv2.bitwise_and(gray, gray, mask=mask)
      12. return Image.fromarray(255 - result) # 反色处理

八、总结与展望

本文实现的Python方案具有三大优势:

  1. 一体化处理:单脚本完成格式转换与OCR识别
  2. 高度可定制:支持20+图片格式、100+语言识别
  3. 性能优化:通过预处理、多线程等技术提升效率

未来发展方向:

  • 集成深度学习模型(如CRNN)提升复杂场景识别率
  • 开发可视化界面降低使用门槛
  • 增加PDF解析与表格识别功能

通过掌握本文技术,开发者可快速构建企业级图片处理系统,在文档管理、数据挖掘等领域创造显著价值。完整代码库已上传GitHub,欢迎交流优化建议。