logo

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

作者:新兰2025.10.10 19:21浏览量:1

简介:本文详解如何使用Python实现图片格式转换与OCR文字识别,涵盖Pillow库转换格式、Tesseract OCR识别文字及完整代码示例,助力开发者高效处理图像数据。

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

在数字化办公和数据处理场景中,图片格式转换与文字识别是两项高频需求。Python凭借其丰富的生态库,能够高效实现图片格式转换(如JPG转PNG)和OCR(光学字符识别)功能。本文将系统介绍如何使用Python完成这两项任务,并提供可复用的代码示例。

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

1.1 Pillow库的核心功能

Pillow是Python中最常用的图像处理库之一,支持超过30种图片格式的读写操作。其核心功能包括:

  • 格式转换:支持JPG、PNG、BMP、GIF等常见格式互转
  • 图像处理:裁剪、旋转、调整大小、色彩空间转换
  • 元数据操作:读取/修改图片的EXIF信息

1.2 基础格式转换实现

  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: 目标格式(如'PNG', 'JPEG')
  8. """
  9. try:
  10. with Image.open(input_path) as img:
  11. # 保存为指定格式
  12. img.save(output_path, format=target_format)
  13. print(f"转换成功:{input_path} → {output_path}")
  14. except Exception as e:
  15. print(f"转换失败:{str(e)}")
  16. # 示例:将JPG转为PNG
  17. convert_image_format("input.jpg", "output.png", "PNG")

1.3 高级转换技巧

  • 批量转换:使用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)

  1. for filename in os.listdir(input_dir):
  2. if filename.lower().endswith(('.jpg', '.jpeg')):
  3. input_path = os.path.join(input_dir, filename)
  4. output_path = os.path.join(output_dir,
  5. os.path.splitext(filename)[0] + f".{target_format.lower()}")
  6. convert_image_format(input_path, output_path, target_format)
  1. - **质量参数控制**(针对JPEG):
  2. ```python
  3. img.save("output.jpg", format="JPEG", quality=95) # 质量范围1-100

二、OCR文字识别:Tesseract的集成应用

2.1 Tesseract OCR安装与配置

  1. 安装Tesseract

    • Windows:下载安装包并添加到PATH
    • Mac:brew install tesseract
    • Linux:sudo apt install tesseract-ocr(基础版)
  2. 安装Python包装库

    1. pip install pytesseract
  3. 配置路径(Windows需设置)

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

2.2 基础文字识别实现

  1. import pytesseract
  2. from PIL import Image
  3. def ocr_image(image_path, lang='chi_sim+eng'):
  4. """
  5. 图片文字识别函数
  6. :param image_path: 图片路径
  7. :param lang: 语言包(中文简体+英文)
  8. :return: 识别结果文本
  9. """
  10. try:
  11. with Image.open(image_path) as img:
  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. result = ocr_image("text_image.png")
  19. print(result)

2.3 识别优化技巧

  • 预处理增强:二值化、去噪、对比度调整
    ```python
    def preprocess_image(image_path):
    img = Image.open(image_path)

    转换为灰度图

    img = img.convert(‘L’)

    二值化处理

    threshold = 150
    img = img.point(lambda x: 0 if x < threshold else 255)
    return img

使用预处理后的图片

processed_img = preprocess_image(“text_image.png”)
text = pytesseract.image_to_string(processed_img)

  1. - **区域识别**:指定识别区域(坐标格式为左上x,左上y,右下x,右下y
  2. ```python
  3. def ocr_region(image_path, box, lang='eng'):
  4. img = Image.open(image_path)
  5. region = img.crop(box)
  6. return pytesseract.image_to_string(region, lang=lang)
  7. # 示例:识别图片中(100,100,300,200)区域的文字
  8. region_text = ocr_region("image.png", (100, 100, 300, 200))

三、完整项目实现:格式转换+OCR一体化

3.1 项目架构设计

  1. project/
  2. ├── input/ # 原始图片
  3. ├── output/ # 转换后的图片
  4. ├── processed/ # OCR处理后的图片
  5. └── main.py # 主程序

3.2 完整代码实现

  1. import os
  2. from PIL import Image
  3. import pytesseract
  4. class ImageProcessor:
  5. def __init__(self):
  6. # 配置Tesseract路径(根据系统调整)
  7. self.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
  8. pytesseract.pytesseract.tesseract_cmd = self.tesseract_cmd
  9. def convert_format(self, input_path, output_dir, target_format):
  10. """转换图片格式并保存"""
  11. if not os.path.exists(output_dir):
  12. os.makedirs(output_dir)
  13. filename = os.path.basename(input_path)
  14. new_filename = os.path.splitext(filename)[0] + f".{target_format.lower()}"
  15. output_path = os.path.join(output_dir, new_filename)
  16. with Image.open(input_path) as img:
  17. img.save(output_path, format=target_format)
  18. return output_path
  19. def ocr_image(self, image_path, output_dir=None, lang='chi_sim+eng'):
  20. """识别图片文字"""
  21. if output_dir:
  22. # 保存处理后的图片
  23. processed_dir = os.path.join(output_dir, "processed")
  24. if not os.path.exists(processed_dir):
  25. os.makedirs(processed_dir)
  26. # 预处理图片
  27. img = Image.open(image_path)
  28. img = img.convert('L')
  29. threshold = 150
  30. img = img.point(lambda x: 0 if x < threshold else 255)
  31. processed_path = os.path.join(processed_dir, os.path.basename(image_path))
  32. img.save(processed_path)
  33. else:
  34. img = Image.open(image_path)
  35. text = pytesseract.image_to_string(img, lang=lang)
  36. return text
  37. def process_batch(self, input_dir, output_base_dir, target_format="PNG"):
  38. """批量处理文件夹中的图片"""
  39. convert_dir = os.path.join(output_base_dir, "converted")
  40. ocr_dir = os.path.join(output_base_dir, "ocr_results")
  41. results = []
  42. for filename in os.listdir(input_dir):
  43. if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp')):
  44. input_path = os.path.join(input_dir, filename)
  45. # 1. 格式转换
  46. converted_path = self.convert_format(input_path, convert_dir, target_format)
  47. # 2. OCR识别
  48. text = self.ocr_image(converted_path, ocr_dir)
  49. results.append({
  50. "original": filename,
  51. "converted": os.path.basename(converted_path),
  52. "text": text
  53. })
  54. return results
  55. # 使用示例
  56. if __name__ == "__main__":
  57. processor = ImageProcessor()
  58. results = processor.process_batch(
  59. input_dir="input",
  60. output_base_dir="output",
  61. target_format="PNG"
  62. )
  63. # 打印识别结果
  64. for result in results:
  65. print(f"\n文件名: {result['original']}")
  66. print(f"转换后: {result['converted']}")
  67. print("识别结果:")
  68. print(result['text'][:200] + "...") # 只显示前200字符

四、实际应用场景与优化建议

4.1 典型应用场景

  1. 文档数字化:将纸质文件扫描件转为可编辑文本
  2. 数据采集:从网页截图、报表图片中提取结构化数据
  3. 自动化流程:结合RPA实现发票、合同自动处理

4.2 性能优化建议

  1. 语言包选择

    • 中文识别:下载chi_sim.traineddata
    • 多语言混合:使用lang='chi_sim+eng'
  2. 处理速度提升

    • 对大图片先缩放再识别
    • 使用多线程处理批量任务
  3. 准确率提升

    • 针对特定场景训练定制模型
    • 结合OpenCV进行更复杂的预处理

五、常见问题解决方案

5.1 识别准确率低

  • 原因:图片质量差、字体特殊、语言包缺失
  • 解决方案
    1. # 使用PSM模式(页面分割模式)
    2. text = pytesseract.image_to_string(
    3. img,
    4. lang='chi_sim+eng',
    5. config='--psm 6' # 假设为统一文本块
    6. )

5.2 格式转换失败

  • 常见原因
    • 图片损坏
    • 不支持的格式
    • 内存不足
  • 调试建议
    1. try:
    2. img = Image.open(input_path)
    3. img.verify() # 验证图片完整性
    4. except Exception as e:
    5. print(f"图片验证失败:{str(e)}")

六、进阶功能扩展

6.1 结合OpenCV实现高级预处理

  1. import cv2
  2. import numpy as np
  3. def cv_preprocess(image_path):
  4. # 读取图片
  5. img = cv2.imread(image_path)
  6. # 转为灰度图
  7. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  8. # 去噪
  9. denoised = cv2.fastNlMeansDenoising(gray, None, 10, 7, 21)
  10. # 二值化
  11. _, binary = cv2.threshold(denoised, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
  12. return binary
  13. # 使用OpenCV处理后转为PIL图像
  14. processed = cv_preprocess("image.png")
  15. pil_img = Image.fromarray(processed)
  16. text = pytesseract.image_to_string(pil_img)

6.2 集成到Web服务

使用Flask创建简单的OCR API:

  1. from flask import Flask, request, jsonify
  2. import base64
  3. from io import BytesIO
  4. app = Flask(__name__)
  5. @app.route('/ocr', methods=['POST'])
  6. def ocr_api():
  7. data = request.json
  8. img_data = base64.b64decode(data['image'].split(',')[1])
  9. img = Image.open(BytesIO(img_data))
  10. text = pytesseract.image_to_string(img, lang='chi_sim+eng')
  11. return jsonify({"text": text})
  12. if __name__ == '__main__':
  13. app.run(host='0.0.0.0', port=5000)

七、总结与展望

Python在图片处理和OCR领域展现出强大的能力,通过Pillow和Tesseract的组合,可以高效实现格式转换和文字识别功能。实际开发中需要注意:

  1. 根据场景选择合适的预处理方法
  2. 合理配置语言包提升识别准确率
  3. 考虑批量处理时的性能优化

未来发展方向包括:

  • 深度学习模型(如CRNN)的集成
  • 实时视频流OCR处理
  • 云端OCR服务的集成方案

本文提供的代码和方案可直接应用于实际项目,开发者可根据具体需求进行调整和扩展。

相关文章推荐

发表评论

活动