Python OCR PDF Extraction

Tesseract Installation

python 复制代码
#!/usr/bin/python3
# 
# Python OCR PDF Extraction
# https://github.com/tesseract-ocr/tesseract
#
# sudo apt install tesseract-ocr
# sudo apt install libtesseract-dev
# pip install pytesseract PyPDF2 pdfplumber opencv-python pillow
# pip install pdf2image
# sudo apt-get install poppler-utils
# sudo apt-get install tesseract-ocr-chi-sim  # Simplified Chinese
# sudo apt-get install tesseract-ocr-chi-tra  # Traditional Chinese
# tesseract --list-langs

import pytesseract
from pdf2image import convert_from_path
from PyPDF2 import PdfReader
import cv2
import numpy as np
from PIL import Image

# Path to Tesseract executable (update to match your system)
pytesseract.pytesseract.tesseract_cmd = '/usr/bin/tesseract'

def preprocess_image(pil_image):
    """
    Preprocesses an image for OCR using OpenCV.
    Converts to grayscale, applies thresholding.
    """
    # Convert PIL image to OpenCV format
    open_cv_image = np.array(pil_image)
    # Convert RGB to BGR (OpenCV default format)
    open_cv_image = cv2.cvtColor(open_cv_image, cv2.COLOR_RGB2BGR)
    # Convert to grayscale
    gray_image = cv2.cvtColor(open_cv_image, cv2.COLOR_BGR2GRAY)
    # Apply binary thresholding
    _, thresh_image = cv2.threshold(gray_image, 128, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
    return thresh_image

def extract_text_from_pdf(pdf_path):
    # First try extracting text from the PDF directly
    reader = PdfReader(pdf_path)
    text = ""
    for page in reader.pages:
        text += page.extract_text() or ""

    # If no text is extracted, assume it's a scanned PDF and use OCR
    if not text.strip():
        images = convert_from_path(pdf_path)
        for image in images:
            # Preprocess image for better OCR results
            preprocessed_image = preprocess_image(image)
            # Convert OpenCV image back to PIL format for Tesseract
            pil_image = Image.fromarray(preprocessed_image)
            # Perform OCR
            text += pytesseract.image_to_string(pil_image, lang='chi_sim')

    return text

# Example usage
pdf_path = "scan_2025-01-02_09.31.pdf"
extracted_text = extract_text_from_pdf(pdf_path)
print(extracted_text)
相关推荐
heimeiyingwang几秒前
【架构实战】API接口防刷与限流策略
开发语言·python·架构
weixin_408099674 分钟前
【保姆级教程】易语言调用 OCR 文字识别 API(从0到1完整实战 + 示例源码)
图像处理·人工智能·后端·ocr·api·文字识别·易语言
小白学大数据14 分钟前
告别复杂 XPath:DeepSeek+Python 爬虫快速实践
开发语言·爬虫·python·selenium
weixin_4080996717 分钟前
【保姆级教程】按键精灵调用 OCR 文字识别 API(从0到1完整实战 + 可运行脚本)
java·前端·人工智能·后端·ocr·api·按键精灵
AI_Claude_code21 分钟前
ZLibrary访问困境方案六:自建RSS/Calibre内容同步服务器的完整指南
运维·服务器·网络·爬虫·python·tcp/ip·http
weixin_4620223525 分钟前
Dancing under the stars: video denoising in starlight
python·计算机视觉
kishu_iOS&AI28 分钟前
机器学习 —— 线性回归(2)
人工智能·python·算法·机器学习·线性回归
网上邻居YY29 分钟前
深度学习DL 之 安装PyTorch·GPU版、CUDA(本人Anaconda、Python、PyCharm已提前安装好)
pytorch·经验分享·python·深度学习·pycharm·学习方法
AI、少年郎31 分钟前
如何用个人电脑快速训练自己的语言模型?MiniMind 全流程实战指南
人工智能·python·神经网络·ai·自然语言处理·大模型·模型训练微调
枫叶林FYL34 分钟前
【Python高级工程与架构实战】项目四 现代ETL编排平台:Airflow + dbt + Snowflake 企业级数据管道架构与实现
人工智能·python·架构·etl