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

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

本站已经建立2652天!

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