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

本站现有博文338篇,共被浏览970802次

本站已经建立2682天!

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