IT评测·应用市场-qidao123.com

标题: 使用easyocr、PyPDF2对图像及PDF文档举行识别 [打印本页]

作者: 曂沅仴駦    时间: 2025-3-5 20:44
标题: 使用easyocr、PyPDF2对图像及PDF文档举行识别
一、概述


本 Python 脚本的重要功能是对当前目录及其子目录下的图片和 PDF 文件举行光学字符识别(OCR)处置惩罚。它使用 easyocr 库处置惩罚图片中的文字,使用 PyPDF2 库提取 PDF 文件中的文本,并将处置惩罚结果保存为文本文件。同时,脚本会记录具体的处置惩罚日志,方便用户跟踪处置惩罚过程和排查问题。
二、环境要求




你可以使用以下命令安装这些依赖库:

收起
bash
  1. pip install easyocr PyPDF2 Pillow
复制代码
三、脚本结构与功能模块

1. 导入必要的库


收起
python
  1. import os
  2. import time
  3. import easyocr
  4. from PyPDF2 import PdfReader
  5. from PIL import Image
复制代码

导入了处置惩罚文件系统、时间、OCR 识别、PDF 读取和图像处置惩罚所需的库。
2. 设置模子下载路径


收起
python
  1. model_storage_directory = './easyocr_models'
  2. os.makedirs(model_storage_directory, exist_ok=True)
复制代码

界说了 easyocr 模子的存储目录,并确保该目录存在。
3. 查抄网络毗连


收起
python
  1. def check_network():
  2.     try:
  3.         import urllib.request
  4.         urllib.request.urlopen('https://www.baidu.com', timeout=5)
  5.         return True
  6.     except:
  7.         return False
复制代码

该函数尝试访问百度网站,以查抄网络毗连是否正常。假如能成功访问,则返回 True,否则返回 False。
4. 初始化 EasyOCR reader


收起
python
  1. try:
  2.     print("Initializing EasyOCR...")
  3.     print(f"Model storage directory: {os.path.abspath(model_storage_directory)}")
  4.    
  5.     if not check_network():
  6.         print("Network connection failed. Please check your internet connection.")
  7.         exit(1)
  8.         
  9.     print("Downloading models (this may take several minutes)...")
  10.     reader = easyocr.Reader(
  11.         ['ch_sim', 'en'],
  12.         model_storage_directory=model_storage_directory,
  13.         download_enabled=True,
  14.         verbose=True
  15.     )
  16.     print("EasyOCR initialized successfully")
  17. except Exception as e:
  18.     print(f"Failed to initialize EasyOCR: {str(e)}")
  19.     exit(1)
复制代码


5. 处置惩罚图片文件


收起
python
  1. def process_image(image_path):
  2.     """处理图片文件"""
  3.     try:
  4.         result = reader.readtext(image_path)
  5.         text = '\n'.join([item[1] for item in result])
  6.         return text
  7.     except Exception as e:
  8.         print(f"Error processing image {image_path}: {str(e)}")
  9.         return ""
复制代码


6. 处置惩罚 PDF 文件


收起
python
  1. def process_pdf(pdf_path):
  2.     """处理PDF文件"""
  3.     try:
  4.         text = ""
  5.         reader = PdfReader(pdf_path)
  6.         for page in reader.pages:
  7.             text += page.extract_text()
  8.         return text
  9.     except Exception as e:
  10.         print(f"Error processing PDF {pdf_path}: {str(e)}")
  11.         return ""
复制代码


7. 保存提取的文本


收起
python
  1. def save_text(text, output_path):
  2.     """保存提取的文本"""
  3.     with open(output_path, 'w', encoding='utf-8') as f:
  4.         f.write(text)
复制代码


8. 主函数 main


收起
python
  1. def main():
  2.     # 尝试多个可能的输出目录位置
  3.     output_folders = [
  4.         './output_text',  # 当前目录
  5.         os.path.expanduser('~/ocr_output'),  # 用户主目录
  6.         os.path.join(os.getcwd(), 'ocr_output')  # 当前工作目录
  7.     ]
  8.    
  9.     output_folder = None
  10.     for folder in output_folders:
  11.         try:
  12.             os.makedirs(folder, exist_ok=True)
  13.             output_folder = folder
  14.             print(f"Using output directory: {os.path.abspath(output_folder)}")
  15.             break
  16.         except Exception as e:
  17.             print(f"Failed to create output directory {folder}: {str(e)}")
  18.    
  19.     if output_folder is None:
  20.         print("Error: Could not create any output directory")
  21.         exit(1)
  22.    
  23.     # 初始化日志
  24.     log_file = os.path.join(output_folder, 'ocr_log.txt')
  25.     # 重定向标准输出到日志文件
  26.     import sys
  27.     class Logger(object):
  28.         def __init__(self, filename):
  29.             self.terminal = sys.stdout
  30.             self.log = open(filename, "a", encoding='utf-8')
  31.         def write(self, message):
  32.             self.terminal.write(message)
  33.             self.log.write(message)
  34.         def flush(self):
  35.             pass
  36.             
  37.     sys.stdout = Logger(log_file)
  38.     print("OCR Processing Log\n")
  39.     print(f"Starting OCR processing at {time.strftime('%Y-%m-%d %H:%M:%S')}")
  40.     # 支持的图片格式
  41.     image_extensions = ['.bmp', '.jpg', '.jpeg', '.png', '.tiff', '.gif']
  42.    
  43.     # 遍历当前目录及子目录
  44.     for root, dirs, files in os.walk('.'):
  45.         for file in files:
  46.             file_path = os.path.join(root, file)
  47.             base_name, ext = os.path.splitext(file)
  48.             
  49.             try:
  50.                 # 处理图片文件
  51.                 if ext.lower() in image_extensions:
  52.                     print(f"Processing image: {file_path}")
  53.                     text = process_image(file_path)
  54.                     output_path = os.path.join(output_folder, f"{base_name}.txt")
  55.                     save_text(text, output_path)
  56.                     print(f"Successfully processed image: {file_path} -> {output_path}")
  57.                     with open(log_file, 'a') as f:
  58.                         f.write(f"Success: {file_path} -> {output_path}\n")
  59.                
  60.                 # 处理PDF文件
  61.                 elif ext.lower() == '.pdf':
  62.                     print(f"Processing PDF: {file_path}")
  63.                     text = process_pdf(file_path)
  64.                     output_path = os.path.join(output_folder, f"{base_name}.txt")
  65.                     save_text(text, output_path)
  66.                     print(f"Successfully processed PDF: {file_path} -> {output_path}")
  67.                     with open(log_file, 'a') as f:
  68.                         f.write(f"Success: {file_path} -> {output_path}\n")
  69.                         
  70.             except Exception as e:
  71.                 error_msg = f"Error processing {file_path}: {str(e)}"
  72.                 print(error_msg)
  73.                 with open(log_file, 'a') as f:
  74.                     f.write(error_msg + "\n")
复制代码


9. 程序入口


收起
python
  1. if __name__ == "__main__":
  2.     main()
复制代码

当脚本作为主程序运行时,调用 main 函数开始执行。
四、使用方法



收起
bash
  1. python ocr_process.py
复制代码
五、注意事项





完成代码
  1. import os
  2. import time
  3. import easyocr
  4. from PyPDF2 import PdfReader
  5. from PIL import Image
  6. # 设置模子下载路径model_storage_directory = './easyocr_models'
  7. os.makedirs(model_storage_directory, exist_ok=True)
  8. # 查抄网络毗连def check_network():
  9.     try:
  10.         import urllib.request
  11.         urllib.request.urlopen('https://www.baidu.com', timeout=5)
  12.         return True
  13.     except:
  14.         return False
  15. # 初始化EasyOCR readertry:
  16.     print("Initializing EasyOCR...")
  17.     print(f"Model storage directory: {os.path.abspath(model_storage_directory)}")
  18.    
  19.     if not check_network():
  20.         print("Network connection failed. Please check your internet connection.")
  21.         exit(1)
  22.         
  23.     print("Downloading models (this may take several minutes)...")
  24.     reader = easyocr.Reader(
  25.         ['ch_sim', 'en'],
  26.         model_storage_directory=model_storage_directory,
  27.         download_enabled=True,
  28.         verbose=True
  29.     )
  30.     print("EasyOCR initialized successfully")
  31. except Exception as e:
  32.     print(f"Failed to initialize EasyOCR: {str(e)}")
  33.     exit(1)
  34. def process_image(image_path):    """处置惩罚图片文件"""    try:        # 使用EasyOCR提取文本        result = reader.readtext(image_path)        # 合并所有识别结果        text = '\n'.join([item[1] for item in result])        return text    except Exception as e:        print(f"Error processing image {image_path}: {str(e)}")        return ""def process_pdf(pdf_path):
  35.     """处理PDF文件"""
  36.     try:
  37.         text = ""
  38.         reader = PdfReader(pdf_path)
  39.         for page in reader.pages:
  40.             text += page.extract_text()
  41.         return text
  42.     except Exception as e:
  43.         print(f"Error processing PDF {pdf_path}: {str(e)}")
  44.         return ""
  45. def save_text(text, output_path):
  46.     """保存提取的文本"""
  47.     with open(output_path, 'w', encoding='utf-8') as f:
  48.         f.write(text)
  49. def main():
  50.     # 尝试多个可能的输出目录位置
  51.     output_folders = [
  52.         './output_text',  # 当前目录
  53.         os.path.expanduser('~/ocr_output'),  # 用户主目录
  54.         os.path.join(os.getcwd(), 'ocr_output')  # 当前工作目录
  55.     ]
  56.    
  57.     output_folder = None
  58.     for folder in output_folders:
  59.         try:
  60.             os.makedirs(folder, exist_ok=True)
  61.             output_folder = folder
  62.             print(f"Using output directory: {os.path.abspath(output_folder)}")
  63.             break
  64.         except Exception as e:
  65.             print(f"Failed to create output directory {folder}: {str(e)}")
  66.    
  67.     if output_folder is None:
  68.         print("Error: Could not create any output directory")
  69.         exit(1)
  70.    
  71.     # 初始化日志
  72.     log_file = os.path.join(output_folder, 'ocr_log.txt')
  73.     # 重定向标准输出到日志文件
  74.     import sys
  75.     class Logger(object):
  76.         def __init__(self, filename):
  77.             self.terminal = sys.stdout
  78.             self.log = open(filename, "a", encoding='utf-8')
  79.         def write(self, message):
  80.             self.terminal.write(message)
  81.             self.log.write(message)
  82.         def flush(self):
  83.             pass
  84.             
  85.     sys.stdout = Logger(log_file)
  86.     print("OCR Processing Log\n")
  87.     print(f"Starting OCR processing at {time.strftime('%Y-%m-%d %H:%M:%S')}")
  88.     # 支持的图片格式
  89.     image_extensions = ['.bmp', '.jpg', '.jpeg', '.png', '.tiff', '.gif']
  90.    
  91.     # 遍历当前目录及子目录
  92.     for root, dirs, files in os.walk('.'):
  93.         for file in files:
  94.             file_path = os.path.join(root, file)
  95.             base_name, ext = os.path.splitext(file)
  96.             
  97.             try:
  98.                 # 处理图片文件
  99.                 if ext.lower() in image_extensions:
  100.                     print(f"Processing image: {file_path}")
  101.                     text = process_image(file_path)
  102.                     output_path = os.path.join(output_folder, f"{base_name}.txt")
  103.                     save_text(text, output_path)
  104.                     print(f"Successfully processed image: {file_path} -> {output_path}")
  105.                     with open(log_file, 'a') as f:
  106.                         f.write(f"Success: {file_path} -> {output_path}\n")
  107.                
  108.                 # 处理PDF文件
  109.                 elif ext.lower() == '.pdf':
  110.                     print(f"Processing PDF: {file_path}")
  111.                     text = process_pdf(file_path)
  112.                     output_path = os.path.join(output_folder, f"{base_name}.txt")
  113.                     save_text(text, output_path)
  114.                     print(f"Successfully processed PDF: {file_path} -> {output_path}")
  115.                     with open(log_file, 'a') as f:
  116.                         f.write(f"Success: {file_path} -> {output_path}\n")
  117.                         
  118.             except Exception as e:
  119.                 error_msg = f"Error processing {file_path}: {str(e)}"
  120.                 print(error_msg)
  121.                 with open(log_file, 'a') as f:
  122.                     f.write(error_msg + "\n")
  123. if __name__ == "__main__":
  124.     main()
复制代码


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 IT评测·应用市场-qidao123.com (https://dis.qidao123.com/) Powered by Discuz! X3.4