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

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

本站已经建立2583天!

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