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 小时前
在服务器中下载 HuggingFace 模型:终极指南
linux·服务器·python·bash·gpu算力
Naiva1 小时前
【小技巧】Python+PyCharm IDE 配置解释器出错,环境配置不完整或不兼容。(小智AI、MCP、聚合数据、实时新闻查询、NBA赛事查询)
ide·python·pycharm
路来了2 小时前
Python小工具之PDF合并
开发语言·windows·python
蓝婷儿2 小时前
Python 机器学习核心入门与实战进阶 Day 3 - 决策树 & 随机森林模型实战
人工智能·python·机器学习
AntBlack2 小时前
拖了五个月 ,不当韭菜体验版算是正式发布了
前端·后端·python
.30-06Springfield2 小时前
决策树(Decision tree)算法详解(ID3、C4.5、CART)
人工智能·python·算法·决策树·机器学习
我不是哆啦A梦2 小时前
破解风电运维“百模大战”困局,机械版ChatGPT诞生?
运维·人工智能·python·算法·chatgpt
WJ.Polar3 小时前
Python数据容器-list和tuple
开发语言·python
qq_229644113 小时前
LucidShape 2024.09 最新
python
开开心心就好3 小时前
免费PDF处理软件,支持多种操作
运维·服务器·前端·spring boot·智能手机·pdf·电脑