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

本站现有博文339篇,共被浏览1001254次

本站已经建立2711天!

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