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

本站现有博文337篇,共被浏览961671次

本站已经建立2673天!

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