logo

Python图片处理全攻略:格式转换与OCR文字识别实战指南

作者:很菜不狗2025.10.10 19:21浏览量:2

简介:本文详细介绍如何使用Python实现图片格式转换与OCR文字识别,涵盖Pillow库的格式转换方法、Tesseract OCR的安装配置及优化技巧,提供完整代码示例和实用建议。

Python图片处理全攻略:格式转换与OCR文字识别实战指南

一、图片格式转换:Pillow库的强大能力

图片格式转换是图像处理的基础需求,Python的Pillow库(PIL)提供了简单高效的解决方案。作为Python Imaging Library的分支,Pillow支持包括JPEG、PNG、BMP、GIF、TIFF等数十种格式的相互转换。

1.1 基础格式转换实现

  1. from PIL import Image
  2. def convert_image_format(input_path, output_path, output_format):
  3. """
  4. 图片格式转换函数
  5. :param input_path: 输入图片路径
  6. :param output_path: 输出图片路径
  7. :param output_format: 目标格式(如'JPEG', 'PNG')
  8. """
  9. try:
  10. with Image.open(input_path) as img:
  11. # 保存为指定格式
  12. img.save(output_path, format=output_format)
  13. print(f"转换成功:{input_path} -> {output_path}")
  14. except Exception as e:
  15. print(f"转换失败:{str(e)}")
  16. # 使用示例
  17. convert_image_format('input.png', 'output.jpg', 'JPEG')

1.2 高级转换技巧

  • 批量转换:使用os.listdir()遍历文件夹实现批量处理
  • 质量参数控制:JPEG格式可通过quality参数调整压缩质量(1-100)
  • 透明度处理:PNG转JPEG时需指定背景色或忽略透明通道
  1. def batch_convert(input_dir, output_dir, output_format, quality=95):
  2. import os
  3. if not os.path.exists(output_dir):
  4. os.makedirs(output_dir)
  5. for filename in os.listdir(input_dir):
  6. if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp')):
  7. input_path = os.path.join(input_dir, filename)
  8. output_path = os.path.join(output_dir,
  9. os.path.splitext(filename)[0] + f'.{output_format.lower()}')
  10. try:
  11. with Image.open(input_path) as img:
  12. if output_format.upper() == 'JPEG' and img.mode in ('RGBA', 'LA'):
  13. # 处理带透明通道的图片
  14. background = Image.new('RGB', img.size, (255, 255, 255))
  15. background.paste(img, mask=img.split()[-1])
  16. background.save(output_path, format='JPEG', quality=quality)
  17. else:
  18. img.save(output_path, format=output_format, quality=quality)
  19. except Exception as e:
  20. print(f"处理{filename}失败:{str(e)}")

二、OCR文字识别:Tesseract的深度应用

Tesseract OCR是由Google维护的开源OCR引擎,支持100多种语言,是Python中实现文字识别的首选方案。

2.1 安装与基础配置

  1. 安装Tesseract

    • Windows:下载安装包并添加到PATH
    • Mac:brew install tesseract
    • Linux:sudo apt install tesseract-ocr(基础版)或sudo apt install tesseract-ocr-[lang](特定语言)
  2. 安装Python包装器

    1. pip install pytesseract

2.2 基础识别实现

  1. import pytesseract
  2. from PIL import Image
  3. def ocr_with_tesseract(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. result = ocr_with_tesseract('text_image.png')
  19. print(result)

2.3 识别优化技巧

  1. 图像预处理
    • 二值化处理:增强文字与背景对比度
    • 降噪:使用高斯模糊或中值滤波
    • 旋转校正:检测并修正倾斜图片
  1. import cv2
  2. import numpy as np
  3. def preprocess_image(image_path):
  4. # 读取图片(使用OpenCV保持通道顺序)
  5. img = cv2.imread(image_path)
  6. # 转换为灰度图
  7. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  8. # 二值化处理
  9. _, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
  10. # 可选:降噪处理
  11. denoised = cv2.medianBlur(binary, 3)
  12. return denoised
  13. def advanced_ocr(image_path, lang='chi_sim+eng'):
  14. processed_img = preprocess_image(image_path)
  15. # 临时保存处理后的图片供Tesseract使用
  16. temp_path = 'temp_processed.png'
  17. cv2.imwrite(temp_path, processed_img)
  18. text = pytesseract.image_to_string(Image.open(temp_path), lang=lang)
  19. return text
  1. 区域识别:通过指定识别区域提高准确率
    1. def ocr_specific_area(image_path, coordinates, lang='chi_sim+eng'):
    2. """
    3. 识别图片指定区域
    4. :param coordinates: (x1, y1, x2, y2) 左上和右下坐标
    5. """
    6. img = Image.open(image_path)
    7. area = img.crop(coordinates)
    8. return pytesseract.image_to_string(area, lang=lang)

三、完整项目实现:格式转换+OCR流水线

  1. import os
  2. from PIL import Image
  3. import pytesseract
  4. import cv2
  5. import numpy as np
  6. class ImageProcessor:
  7. def __init__(self, ocr_lang='chi_sim+eng'):
  8. self.ocr_lang = ocr_lang
  9. def convert_format(self, input_path, output_path, output_format, quality=95):
  10. """格式转换核心方法"""
  11. try:
  12. with Image.open(input_path) as img:
  13. if output_format.upper() == 'JPEG' and img.mode in ('RGBA', 'LA'):
  14. background = Image.new('RGB', img.size, (255, 255, 255))
  15. background.paste(img, mask=img.split()[-1])
  16. background.save(output_path, format='JPEG', quality=quality)
  17. else:
  18. img.save(output_path, format=output_format, quality=quality)
  19. return True
  20. except Exception as e:
  21. print(f"格式转换错误:{str(e)}")
  22. return False
  23. def preprocess_for_ocr(self, image_path):
  24. """OCR专用预处理"""
  25. img = cv2.imread(image_path)
  26. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  27. _, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
  28. return binary
  29. def recognize_text(self, image_path):
  30. """文字识别核心方法"""
  31. processed = self.preprocess_for_ocr(image_path)
  32. temp_path = 'temp_ocr.png'
  33. cv2.imwrite(temp_path, processed)
  34. try:
  35. text = pytesseract.image_to_string(Image.open(temp_path), lang=self.ocr_lang)
  36. os.remove(temp_path) # 清理临时文件
  37. return text
  38. except Exception as e:
  39. print(f"OCR识别错误:{str(e)}")
  40. return None
  41. def process_pipeline(self, input_path, output_format, output_text_path=None):
  42. """完整处理流水线"""
  43. # 1. 格式转换
  44. base_name = os.path.splitext(os.path.basename(input_path))[0]
  45. converted_path = f"{base_name}_converted.{output_format.lower()}"
  46. if not self.convert_format(input_path, converted_path, output_format):
  47. return None
  48. # 2. 文字识别
  49. text = self.recognize_text(converted_path)
  50. # 3. 保存识别结果
  51. if output_text_path and text:
  52. with open(output_text_path, 'w', encoding='utf-8') as f:
  53. f.write(text)
  54. return {
  55. 'converted_image': converted_path,
  56. 'recognized_text': text,
  57. 'status': 'success'
  58. }
  59. # 使用示例
  60. processor = ImageProcessor(ocr_lang='chi_sim+eng')
  61. result = processor.process_pipeline(
  62. input_path='input_doc.png',
  63. output_format='JPEG',
  64. output_text_path='output_text.txt'
  65. )
  66. print(result)

四、实际应用建议

  1. 性能优化

    • 对大图片先缩放再识别(建议宽度不超过2000px)
    • 使用多线程处理批量任务
    • 对于固定格式的文档,可预先训练Tesseract模型
  2. 准确率提升

    • 中文识别建议使用chi_sim(简体)或chi_tra(繁体)
    • 复杂背景图片可尝试调整二值化阈值
    • 表格类图片建议先检测表格线再分区识别
  3. 错误处理

    • 添加文件存在性检查
    • 实现重试机制应对临时性错误
    • 记录处理日志便于问题追踪

五、扩展功能实现

  1. PDF转图片再OCR
    ```python
    from pdf2image import convert_from_path

def pdf_to_text(pdf_path, output_text_path, dpi=300, lang=’chi_sim+eng’):
images = convert_from_path(pdf_path, dpi=dpi)
full_text = []
processor = ImageProcessor(lang)

  1. for i, image in enumerate(images):
  2. temp_path = f'temp_page_{i}.png'
  3. image.save(temp_path, 'PNG')
  4. text = processor.recognize_text(temp_path)
  5. if text:
  6. full_text.append(text)
  7. os.remove(temp_path)
  8. if full_text:
  9. with open(output_text_path, 'w', encoding='utf-8') as f:
  10. f.write('\n'.join(full_text))
  1. 2. **多语言混合识别**:
  2. ```python
  3. # 安装额外语言包(如日文)
  4. # sudo apt install tesseract-ocr-jpn
  5. # 然后使用lang='jpn+eng'

六、常见问题解决方案

  1. Tesseract找不到路径

    • Windows需设置pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
  2. 中文识别率低

    • 确认已安装中文语言包
    • 尝试lang='chi_sim'(简体)或'chi_tra'(繁体)
    • 对低质量图片增加预处理步骤
  3. 内存不足

    • 处理大文件时分块读取
    • 及时关闭不再使用的图片对象
    • 增加系统交换空间

通过本文介绍的完整方案,开发者可以快速构建起从图片格式转换到文字识别的完整处理流程。实际项目中,建议根据具体需求调整预处理参数和识别策略,对于关键业务场景,可考虑结合商业OCR API实现更高准确率的识别。

相关文章推荐

发表评论

活动