Embedding Images and Tables for RAG: A Practical Guide

    Learn how to make images and tables searchable, citable evidence in retrieval-augmented generation. This guide covers layout analysis, structured table parsing, image descriptions, embedding alignment, retrieval, and quality checks, with an emphasis on preserving structure and traceability.

    In retrieval-augmented generation (RAG), the quality of the vector index directly affects whether the system retrieves the right evidence. Many teams chunk and embed only the document body. That approach often breaks down with annual reports, manuals, research papers, and policy documents: key figures appear in tables, while important constraints are embedded in diagrams or scanned pages. Text-only pipelines either discard this information or flatten the layout into an incoherent sequence of characters.

    Closing this gap requires a multimodal embedding pipeline. Non-text information must become searchable, citable, and traceable text representations or joint embeddings, with a retrieval strategy that aligns them with the document’s text embeddings.

    1. Identify Where Information Is Lost

    Documents typically pass through five stages before entering a vector index: parsing, cleaning, chunking, embedding, and ingestion. Images and tables often lose information during the first three stages.

    During parsing, extracting only visible characters can scramble multi-column reading order, mix headers and footers into the body, and split tables across pages into unrelated fragments. During chunking, fixed-length cuts can separate column headers from data rows, leaving retrieved numbers without their field meanings. During embedding, models trained primarily on natural language may not adequately represent formulas, merged cells, or diagrams. Similarity search can then favor passages with similar wording but unrelated facts.

    The goal is therefore not to turn everything into one long text string. It is to preserve structure. Each evidence unit should identify its source page, element type, and relationship to surrounding fields or context, so it can be cited during generation.

    2. Use Layout Analysis as the Common Entry Point

    Start by reconstructing the document as a sequence of typed elements rather than a single string. Common elements include headings, paragraphs, lists, tables, images, formulas, footnotes, and page numbers.

    Multi-column pages should be reordered according to reading order, not simply concatenated from left to right by coordinates. Scanned documents require orientation correction, noise reduction, and optical character recognition (OCR) before layout analysis. For digitally generated documents, prioritize the text layer and fall back to image-based processing when extraction fails.

    Keep two output representations:

    • Readable markup: Use heading levels, lists, and table syntax to preserve structure for people and language models.
    • Structured records: Store element type, page number, reading order, and bounding box.

    Coordinates support review and interface highlighting. When a user clicks an answer citation, the application can return to the relevant region on the original page rather than showing an isolated excerpt.

    Fonts, encodings, and scan quality vary considerably. Record parsing confidence throughout the pipeline. Low-confidence pages should go through manual sampling or a second recognition pass instead of silently entering the index. Otherwise, incorrect characters can contaminate retrieval while still producing high similarity scores.

    3. Parse Tables into Structured Semantic Representations

    Tables are among the easiest RAG inputs to parse superficially without making them useful. Tables with visible borders are relatively straightforward. Borderless tables, dense layouts, merged cells, cross-page continuations, and handwritten notes are more difficult.

    The processing order should be: recover the logical grid, restore semantic meaning, and only then generate embeddings.

    The logical grid records each cell’s row, column, and span. For merged headers, propagate the header meaning to the corresponding data cells rather than leaving it implicit or blank. For cross-page tables, identify repeated headers and join the continuation pages into one logical table. Retain the physical page references so citations remain locatable.

    Semantic processing should include at least three steps:

    1. Distinguish the table title, headers, data region, and notes.
    2. Convert the two-dimensional table into a consistent textual view. For example, represent entries as “metric—dimension—value—unit—period” key-value descriptions rather than embedding a string of numbers.
    3. Preserve the original grid. Questions requiring exact numbers should return to the grid for verification.

    Storing only rewritten text helps retrieval but weakens auditability. Storing only the grid makes field relationships difficult for the embedding model to understand. Keep both as linked views of the same table object.

    Do not divide a logical table into unrelated, non-overlapping windows. Large tables can be split by a business key or row group, but every slice must repeat the table title and headers. Otherwise, a value such as “the growth rate in the third row” has no identifiable subject in the embedding space.

    4. Represent Images Through Both Vision and Language

    Images cannot be passed directly to a text-only embedding model. Three approaches are practical and are often combined.

    Extract the Text Layer

    Use OCR to convert labels, axis titles, legends, and flowchart nodes into short text representations. This may already capture much of the useful information in architecture diagrams, interface screenshots, and annotated illustrations.

    Generate Visual Descriptions

    Use a vision-language model to produce an objective description of the image: its type, main objects, visible text, and possible references from surrounding paragraphs, such as “the figure above” or “Figure 3.”

    Constrain descriptions to what is visibly present. The model should not fill in missing values based on general knowledge. Store each description with the original image and its page reference.

    Use Cross-Modal Embeddings

    When information resides primarily in visual structure, joint image-text embeddings can place text queries and image regions in a comparable space.

    If production maintains only one text vector index, embed image descriptions in that text space and store image embeddings in a secondary index, then fuse retrieval results. Do not assume that different embedding types are inherently comparable. Scores from unaligned or uncalibrated spaces should not be added directly.

    Also distinguish diagrams and photographs from decorative graphics. Header logos and non-informative separators do not need to be indexed; otherwise, they can consume retrieval slots without contributing evidence.

    5. Align Representations with Text Retrieval

    Alignment means that a natural-language query can retrieve table descriptions, image descriptions, and body paragraphs under a consistent retrieval strategy.

    Use the same text embedding model and normalization method for body text, table views, and image descriptions. If image-specific embeddings are also used, keep them in a separate index. Use the corresponding query-side text encoder or a small labeled question-answer set to calibrate scores before choosing fusion weights.

    Each vector record should carry consistent metadata:

    • Document identifier and version
    • Page number
    • Element type
    • Section path
    • Table or figure identifier
    • Confidence
    • Source coordinates

    Metadata filters—for example, restricting retrieval to the current version of a policy—are often more reliable than encoding every constraint into the vector itself.

    Chunk by element structure, not character count alone:

    • Paragraphs: Use semantic boundaries with controlled overlap.
    • Tables: Use logical table slices.
    • Images: Combine the figure caption, description, and nearby explanatory paragraphs.

    Nearby explanations matter because the body may contain a rule such as “As shown in the figure, shut down the machine when the temperature exceeds the threshold.” That rule may not be recoverable from the image alone.

    6. Retrieve and Generate with Traceable Evidence

    Retrieval does not have to consist of a single vector search. A more robust approach uses multiple retrieval paths for text chunks, table views, and image descriptions, then deduplicates results using document and page metadata and filters by version.

    For questions requiring exact numbers, retrieve the original table grid after finding the relevant table. Do not rely on the generation model to reproduce an approximate statement from the embedded text.

    Prompts should require the model to distinguish body-text statements from table or figure evidence. When evidence is insufficient, it should identify what is missing rather than treating an uncertain image description as a measured value.

    Citations should include at least the document name, version, and page number. Source coordinates can support precise navigation in the user interface.

    Object storage is suitable for original files, intermediate parsing outputs, and image crops. The vector database should hold embeddings and metadata. Preserve parsing results immutably by document version. When a policy or manual changes, reingest the complete version to avoid mixing old and new table headers in the same index.

    The same separation applies when using object storage, vector retrieval, and inference services on Baidu AI Cloud: decouple storage, indexing, and generation, and keep parsing artifacts available for review and reprocessing.

    7. Validate Quality and Diagnose Common Failures

    Before deployment, test with real questions rather than judging whether sample parsing outputs look correct. The evaluation set should cover:

    • Totals in cross-page tables
    • The scope of merged-cell headers
    • Multi-column reading order
    • Thresholds shown in figures
    • References where an image appears before its explanation

    Useful metrics include whether the correct page was retrieved, whether key numbers match the source, and whether the system declines to answer when evidence is absent.

    Four common failures are:

    • Missing headers cause numbers to be attributed to the wrong fields.
    • Borderless tables are recognized as ordinary paragraphs.
    • Image descriptions introduce unsupported details.
    • Fixed-length chunking separates headers from data.

    These problems usually require changes to element classification, logical table reconstruction, or slicing strategy—not merely a different prompt.

    The following pseudocode illustrates the pipeline boundaries without depending on a specific API:

    1. def ingest(doc):
    2. elements = layout_parse(doc) # Headings, paragraphs, tables, and figures, with pages and coordinates
    3. records = []
    4. for el in elements:
    5. if el.type == "table":
    6. grid = recover_grid(el) # Merged cells and cross-page table continuations
    7. view = table_to_semantic_text(grid)
    8. records.append(chunk(view, meta=el, payload=grid))
    9. elif el.type == "figure":
    10. if is_decorative(el):
    11. continue
    12. caption = ocr_and_caption(el) # Describe only visible content
    13. neighbor = nearby_paragraphs(el)
    14. records.append(chunk(caption + neighbor, meta=el))
    15. else:
    16. records.append(chunk(el.text, meta=el))
    17. return embed_and_upsert(records)

    8. Make Practical Implementation Trade-Offs

    Not every knowledge base needs image embeddings. If nearly all useful information in its tables and figures can be represented as text and grids, a text index is simpler to operate and troubleshoot.

    Image indexes are more appropriate for materials that lose substantial information when converted to text, such as engineering drawings, medical-image documentation, and interface screenshots. Evaluate their storage and latency requirements separately.

    Version the parsing, description, and embedding components. After upgrading models or rules, run the same acceptance questions again and confirm that numeric-answer quality has not regressed before switching the production index. Prioritize manual sampling for low-confidence outputs, cross-page tables, and images containing numbers.

    Reliable RAG over complex documents requires treating images and tables as first-class evidence, not noise attached to the body text. The essentials are accurate layout reconstruction, paired semantic and grid views for tables, restrained image descriptions, consistent metadata, and traceable multi-path retrieval. With these foundations, non-text content becomes citable evidence rather than a gap in the retrieval pipeline.