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

本站现有博文332篇,共被浏览887147

本站已经建立2590天!

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