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)
相关推荐
砚底藏山河12 分钟前
沪深A股:如何获取基金持股数据
java·python·数据分析·maven
goldenrolan26 分钟前
学习型红外控制系统稳定性挂测工装专项总结
软件测试·python·stm32·嵌入式·红外
小小龙学IT1 小时前
Apache Airflow 2.x 深度指南:用 Python 编排一切的现代化工作流引擎
开发语言·python·apache
HappyAcmen1 小时前
7.faiss-cpu向量库安装
python·faiss
你是个什么橙1 小时前
Python入门学习2:Python 基础语法全解析——从代码结构到输入输出
开发语言·python·学习
小白学大数据1 小时前
Python + 大模型行业资讯自动化摘要流水线完整工程实现方案
开发语言·python·自动化
beethobe2 小时前
PythonQt 学习之旅(一):从零构建 C++ 与 Python 的桥梁
c++·python·学习
广州智造2 小时前
如何在HyperMesh运行Python脚本及查找Python API帮助
python·仿真·cae·hypermesh·optistruct
cooldog123pp2 小时前
cplex完全安装手册,适配matlab和python!
人工智能·python·matlab·cplex
TechWayfarer2 小时前
苏超赛事网站安全防护:WAF、DDoS与仿冒页面如何联动治理
网络·python·安全·flask·ddos