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

本站现有博文336篇,共被浏览939239

本站已经建立2649天!

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