EADST

Image2Text: Automating Document Layout Analysis with Python and LayoutParser

Image2Text: Automating Document Layout Analysis with Python and LayoutParser

import cv2
import layoutparser as lp
import os
import json
from PIL import Image
import numpy as np

def to_serializable(obj):
    if isinstance(obj, (np.float32, np.float64)):
        return float(obj)
    elif isinstance(obj, np.ndarray):
        return obj.tolist()
    else:
        return obj

def process_image(image_path, model):
    # Read and preprocess the image
    image = cv2.imread(image_path)
    image = image[..., ::-1]  # Convert from BGR to RGB

    # Use the model to detect layout
    layout = model.detect(image)

    # Convert layout objects to a serializable format
    layout_data = []
    for obj in layout:
        obj_dict = obj.to_dict()
        # Iterate through the dictionary, converting all numpy data types to serializable types
        obj_dict_serializable = {key: to_serializable(value) for key, value in obj_dict.items()}
        layout_data.append(obj_dict_serializable)

    return layout_data

def save_layout_to_json(layout_data, json_path):
    # Save layout data to a JSON file
    with open(json_path, 'w') as json_file:
        json.dump(layout_data, json_file)

# Load the model
model = lp.PaddleDetectionLayoutModel(
    config_path="lp://PubLayNet/ppyolov2_r50vd_dcn_365e_publaynet/config",
    threshold=0.5,
    label_map={0: "Text", 1: "Title", 2: "List", 3: "Table", 4: "Figure"},
    enforce_cpu=False,
    enable_mkldnn=True
)

def process_folder(folder_path):
    # Iterate through all files and subfolders in the folder
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.lower().endswith('.jpg'):  # Check if it's a JPG file
                file_path = os.path.join(root, file)
                layout_data = process_image(file_path, model)  # Process the image

                # Create JSON file path
                json_path = os.path.splitext(file_path)[0] + '.json'
                save_layout_to_json(layout_data, json_path)  # Save layout data as JSON


# Specify the folder path to process
folder_path = '/your_folder_path/'
process_folder(folder_path)
相关标签
About Me
XD
Goals determine what you are going to be.
Category
标签云
阿里云 SPIE icon PyCharm Ubuntu Qwen2.5 Math Input Shortcut MD5 BF16 Search VSCode Domain Video v2ray SQL Dataset VGG-16 TTS FP32 FP8 图形思考法 Django Freesound SAM LaTeX Tracking Quantization 净利润 多线程 LoRA Docker diffusers Bin Distillation 音频 Firewall Random Linux 论文速读 财报 算法题 Baidu Miniforge OCR Pickle Safetensors Michelin Zip CLAP WebCrawler ModelScope Logo Jupyter 版权 继承 Github Cloudreve Attention FlashAttention BTC Qwen2 CEIR llama.cpp git SQLite 飞书 CSV Paddle Website Paper Use tqdm Diagram Vim 关于博主 TSV Algorithm Clash VPN QWEN Land Jetson GoogLeNet ResNet-50 CV Pandas 递归学习法 域名 云服务器 Color HaggingFace hf mmap SVR JSON Git FastAPI Google uWSGI HuggingFace Tiktoken Sklearn GGML 强化学习 Qwen Nginx Numpy Transformers PIP Markdown Bert Windows Gemma LLM 公式 Plate Image2Text tar Claude Bipartite Review Pytorch ONNX 论文 Proxy C++ scipy UI GPTQ Interview DeepStream Breakpoint 搞笑 torchinfo 图标 v0.dev Disk PDF Agent YOLO Conda RL GPT4 GIT Password AI Food InvalidArgumentError 报税 CTC EXCEL Mixtral DeepSeek FP16 uwsgi IndexTTS2 printf Heatmap Hilton ChatGPT API Knowledge Datetime Template Streamlit Bitcoin logger Base64 Translation Magnet NLTK Ptyhon CUDA Pillow COCO git-lfs XML Tensor Python LeetCode Plotly BeautifulSoup Card ms-swift RAR UNIX OpenCV Permission OpenAI PyTorch PDB NLP 多进程 第一性原理 顶会 Animate Crawler CC News Llama Anaconda CAM Rebuttal NameSilo TensorRT 签证 RGB Quantize WAN TensorFlow Vmess Hotel LLAMA FP64 XGBoost 证件照 transformers Augmentation Web Excel Data Statistics 腾讯云 Hungarian
站点统计

本站现有博文333篇,共被浏览913719

本站已经建立2616天!

热门文章
文章归档
回到顶部