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

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

本站已经建立2616天!

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