使用 EasyOCR 识别 PDF 中的文字

背景:

在读取PDF上文字的时候,发现有些pdf是图片格式的,常规的pdf库是提取不到的。因此考虑使用OCR进行提取。

依赖:

安装 EasyOCR 和相关依赖

首先,您需要安装 EasyOCRpdf2image(用于将 PDF 转换为图像):

pip install easyocr pdf2image requests numpy


安装 poppler(如果尚未安装)

由于 pdf2image 依赖 poppler 来处理 PDF 文件,因此需要安装 poppler。在 macOS 上,您可以使用 Homebrew 进行安装:

brew install poppler

在 Linux 系统上,您可以使用以下命令安装 poppler

sudo apt-get install poppler-utils

最终代码

import requests
from pdf2image import convert_from_path
import easyocr
import numpy as np
import tempfile
import os

def download_pdf(url, save_path):
    response = requests.get(url)
    with open(save_path, 'wb') as f:
        f.write(response.content)

def ocr_pdf_using_easyocr(url):
    # Step 1: Download the PDF
    with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as temp_pdf:
        download_pdf(url, temp_pdf.name)

    # Step 2: Convert PDF to images
    images = convert_from_path(temp_pdf.name)

    # Step 3: Initialize EasyOCR
    reader = easyocr.Reader(['ch_sim', 'en'])  # Simplified Chinese and English

    # Step 4: Perform OCR on each image
    all_text = []
    for image in images:
        # Convert PIL Image to numpy array
        image_np = np.array(image)
        result = reader.readtext(image_np)
        for (bbox, text, prob) in result:
            all_text.append(text)
    
    # Clean up the temporary PDF file
    os.remove(temp_pdf.name)

    return "\n".join(all_text)

# Usage
url = "./0b3b9b0c0b594c2fb7ea28adb80c1163.pdf"
extracted_text = ocr_pdf_using_easyocr(url)
print(extracted_text)

提取成功

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值