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)
相关推荐
宿州派大星1 小时前
Python 音视频处理流水线:视频分离音频 + 讯飞转写 + 星火大模型解析(附完整代码与踩坑指南)
开发语言·python·音视频
I Am a robert girl1 小时前
DiffRAC:当视频“呼吸”有了节拍器——重复动作计数的新范式
python·深度学习·计算机视觉·视频分析·视频扩散模型·重复动作计数
开开心心就好2 小时前
定时结束进程的小工具,到点还能关机
linux·运维·服务器·智能手机·pdf·电脑·word
郝学胜-神的一滴2 小时前
Effective Python 条款47:吃透惰性属性
大数据·开发语言·数据库·人工智能·python·算法·oracle
有个傻瓜2 小时前
容器里时间凭空差 8 小时:naive 与 aware 时区混用排错复盘与四种方案实测
python·docker·springboot·时区排错·naive/aware
心流剑2 小时前
从零打造带降级路由的 Agentic RAG 校园智能体(附前端终端UI实战)
python·ai·rag
天远数科3 小时前
零信任架构实战:基于天远车辆过户详版查询构建自动化抵押车权属合规审查网关
人工智能·python·架构·自动化
badhope4 小时前
3 个 Agent 并行发文章:我用 SQLite 任务表止住重复
后端·python·ai编程
战6174 小时前
Python 基础算法:三种排序、二分查找与递归
开发语言·python·算法
databook4 小时前
马尔可夫链入门:状态、转移概率与无记忆性
python·机器学习·数据分析