Option to keep a picture that the layout model detects inside a larger picture

Open
#5,580 1 comment 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 2 days

@xixi-box is already working on this.

Since Nov 25, 2026.

  • #5581 by @xixi-box — open

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
25/100
Issue type
Feature
Clarity
Mostly clear
Activity status
Stale
Tech stack
python

Research direction

Start with docling/utils/layout_postprocessor.py and the LayoutPostprocessorOptions definition in docling/datamodel/pipeline_options.py; the issue describes the overlap merge and a candidate opt-in behavior. Read the related discussion in #1437 and the open pull request #5581 before assessing next steps. Done means the maintainers settle the trade-off and option location, then the behavior preserves contained pictures when enabled while the default remains unchanged.

Written by the indexing model from the issue text.

Description

enhancement image priority:medium
Requested feature

We ask for an opt-in option that keeps a picture inside a larger picture as its own PictureItem, for users who want inner elements (signatures, stamps, logos) classified on their own. The default stays as it is.

Today LayoutPostprocessor merges a picture that lies inside another picture, so only the outer picture reaches enrichment. Without a model:

from docling_core.types.doc import BoundingBox, DocItemLabel, Size

from docling.datamodel.base_models import Cluster, Page
from docling.datamodel.pipeline_options import LayoutPostprocessorOptions
from docling.utils.layout_postprocessor import LayoutPostprocessor


def pic(i, l, t, r, b, conf):
    return Cluster(id=i, label=DocItemLabel.PICTURE, confidence=conf, bbox=BoundingBox(l=l, t=t, r=r, b=b))


page = Page(page_no=1, size=Size(width=1000, height=1000))
clusters = [pic(0, 50, 50, 900, 900, 0.95), pic(1, 300, 780, 480, 830, 0.90)]
out = LayoutPostprocessor(page, clusters, LayoutPostprocessorOptions()).postprocess()
print([(c.id, c.label.value) for c in out])

Output: [(0, 'picture')]. The inner picture is gone.

On the model path (synthetic scanned drawing with a signature in its title block; script below), the layout model detects the drawing (0.943) and the signature (0.560), both above the 0.5 picture threshold. The output has one PictureItem, engineering_drawing 0.914. A tight crop of the signature gives signature 0.994.

Public example. O. & W. Wright, Flying Machine, US 821,393, sheet 1, public domain (NARA via Wikimedia Commons): https://upload.wikimedia.org/wikipedia/commons/4/40/821393_-_Flying_Machine_-_Wright_Brothers_-_NARA_-_2524937_%28page_1%29.jpg. Image input, main 5bfd7c18, CPU, default options plus do_picture_classification=True. The layout model detects the drawing as a picture (0.708) and the signed inventors' block (x 0.566–0.786, y 0.781–0.858 of the page) as a picture (0.704). The block is more than 80 % inside the drawing, so the merge keeps only the drawing: one PictureItem, engineering_drawing 0.9994. A tight crop of the block gives signature 0.874.

Cause. All lines are in docling/utils/layout_postprocessor.py at v2.152.0. The file is identical at main 5bfd7c18.

  1. _process_special_clusters sends all pictures to _remove_overlapping_clusters(..., "picture") (L299-304).
  2. That method joins two pictures when IoU > 0.8 or when either containment > 0.8 (L84-105, L555-556). A picture inside another picture has containment 1.0.
  3. Each group keeps one cluster. On the synthetic page the outer picture is 0.383 more confident, so it wins (L506-514). On the Wright sheet the gap is 0.004, so the larger picture wins (L541-547).

By contrast, a picture inside a TABLE is kept on purpose (L447-480), and a picture inside a FORM is nested since #4064. No unit test covers picture-in-picture; the e2e groundtruth depends on the merge (2206.01062.json, page 9).

Trade-off: #1437. With such an option on, multi-panel figures split into panels next to the composite, which #1437 reports as a bug. With the shape below, on the upstream test PDFs (26 files, 108 pages, layout stage only), 12 pages change and their pictures go from 27 to 55, almost all sub-panels. 2206.01062.pdf page 9 goes from 1 to 6 pictures and 6 Markdown image placeholders. The option only suits users who accept this.

Cost (measured, emulated patch, main 5bfd7c18, CPU, default pipeline plus picture classification, the same 108 pages). The option adds 28 pictures on 12 pages, so 28 more classifier calls: about 1 to 1.5 s in total against about 200 s of conversion. Layout inference does not change, because the model already proposes these pictures. The change in total wall time and peak memory stays inside run-to-run noise. If picture description is enabled, it runs 9 more times: only 9 of the 28 added pictures reach its 5 % of page minimum.

Candidate shape. A boolean, off by default. With it on, containment no longer joins two pictures; only IoU > 0.8 does. This uses the existing overlap_threshold, and _remove_overlapping_clusters already takes containment_threshold as a parameter (L556). No new number. A text inside both pictures goes to the tightest one only (as the container code does, L350-357). Measured with a patch without the text rule on the synthetic page: the signature becomes its own PictureItem, signature 0.974, and one text appears twice.

Related: #4149 (measured, head 9cd1cfdb). It deletes the rule that drops a picture covering more than 90 % of the page (L285-297). Today a picture inside such a page-sized picture survives; with #4149 the page-sized picture is kept, unless it is a wrapper, and absorbs it. The synthetic page (outer at 69 %) is the same with or without #4149.

Questions:

  1. Given #1437, would you accept such an option at all?
  2. If yes, where should it live: a postprocessor option forwarded from the layout options (as keep_empty_clusters is in standard_pdf_pipeline.py L669-678), or a layout option only?

Versions: docling 2.152.0, docling-core 2.108.0, Python 3.14.6, CPU; same on main.

Alternatives
  • Run DocumentPictureClassifier on a crop the user selects. This works (signature 0.994), but the user must know where the element is.
  • A better layout model (#1437). It does not tell a wanted element from an unwanted panel.
Full reproducer (synthetic page, model path)

The script draws its own one-page PDF with Pillow. It converts the PDF with the default PDF pipeline plus do_picture_classification. It reads LayoutPostprocessor input and output by wrapping two methods (instrumentation only). Run with python nested_picture_repro.py OUT_DIR.

"""A small picture inside a bigger picture never gets its own classification.

Self-contained: the script draws its own one-page scanned-style PDF (a line
drawing with a handwritten-style signature in its title block, no text layer),
converts it with docling's default PDF pipeline plus picture classification,
and then shows where the signature is lost.

  Part 1  end to end: the PictureItems docling outputs and their classes.
  Part 2  the classifier on a tight crop of the signature, same classifier,
          same page rendering scale (DocumentPictureClassifier.images_scale).
  Part 3  what the layout model proposes for the signature region: raw
          clusters (read off LayoutPostprocessor's input) at the default engine
          score_threshold and at a lowered one.
  Part 4  no model: hand-built clusters through the real LayoutPostprocessor,
          an outer picture with a fully contained inner picture.

Run:  python nested_picture_repro.py [OUT_DIR]
Needs: docling (standard install). Downloads the layout and picture-classifier
models on first use. Runs on CPU. Tested with Pillow 13.0.0 (uses ImageFont.load_default(size=...)).
"""

import math
import random
import sys
import tempfile
from pathlib import Path

from PIL import Image, ImageDraw, ImageFont

import docling.utils.layout_postprocessor as lpp
from docling.datamodel.accelerator_options import AcceleratorDevice, AcceleratorOptions
from docling.datamodel.base_models import Cluster, InputFormat, Page
from docling.datamodel.pipeline_options import (
    LayoutObjectDetectionOptions,
    LayoutPostprocessorOptions,
    PdfPipelineOptions,
)
from docling.document_converter import DocumentConverter, PdfFormatOption
from docling.models.stages.picture_classifier import document_picture_classifier as dpc
from docling_core.types.doc import BoundingBox, CoordOrigin, DocItemLabel, PictureItem, Size

DPI = 200
PAGE_W, PAGE_H = int(8.5 * DPI), int(11 * DPI)
# Signature box in page fractions (top-left origin): l, t, r, b.
SIGNATURE = (0.30, 0.765, 0.47, 0.805)
STROKE = 4
INK = 0


def font(size):
    return ImageFont.load_default(size=size)


def draw_signature(d, box, rng):
    """A slanted cursive-style scribble with an underline flourish."""
    l, t, r, b = box
    w, h = r - l, b - t
    loops, slant, seed, n = 7, 1.2, 4, 900
    pts = []
    for i in range(n):
        u = i / (n - 1) * loops * 2 * math.pi
        amp = 0.35 + 0.15 * math.sin(u * 0.37 + seed)
        x = (u / (loops * 2 * math.pi)) * 0.85 + 0.06 * math.sin(u)
        y = 0.55 - amp * math.cos(u) * (1.0 if (int(u / (2 * math.pi)) % 3) else 1.4)
        x += slant * (0.55 - y) * 0.25
        pts.append((l + x * w, t + y * h))
    d.line(pts, fill=INK, width=STROKE, joint="curve")
    d.line([(l + 0.02 * w, t + 0.92 * h), (l + 0.55 * w, t + 0.85 * h), (l + 0.98 * w, t + 0.95 * h)],
           fill=INK, width=max(1, STROKE - 1), joint="curve")


def draw_page():
    rng = random.Random(7)
    im = Image.new("L", (PAGE_W, PAGE_H), 255)
    d = ImageDraw.Draw(im)
    x0, y0, x1, y1 = int(0.06 * PAGE_W), int(0.06 * PAGE_H), int(0.92 * PAGE_W), int(0.86 * PAGE_H)
    d.rectangle([x0, y0, x1, y1], outline=0, width=5)
    outline = [(x0 + 150, y0 + 160), (x0 + 520, y0 + 160), (x0 + 520, y0 + 80), (x1 - 380, y0 + 80),
               (x1 - 380, y0 + 260), (x1 - 160, y0 + 260), (x1 - 160, int(0.66 * PAGE_H)),
               (x0 + 260, int(0.66 * PAGE_H)), (x0 + 260, int(0.45 * PAGE_H)), (x0 + 150, int(0.45 * PAGE_H))]
    d.polygon(outline, outline=0, width=5)
    for k in range(14):
        yy = y0 + 300 + k * 70
        d.line([(x0 + 300, yy), (x1 - 200, yy + rng.randint(-6, 6))], fill=0, width=2)
    for _ in range(60):
        cx, cy = rng.randint(x0 + 300, x1 - 220), rng.randint(y0 + 300, int(0.64 * PAGE_H))
        rr = rng.randint(8, 30)
        d.ellipse([cx - rr, cy - rr, cx + rr, cy + rr], outline=0, width=2)
    hatch = Image.new("L", im.size, 255)
    hd = ImageDraw.Draw(hatch)
    for k in range(-60, 80):
        xa = x0 + k * 26
        hd.line([(xa, y1), (xa + (y1 - y0), y0)], fill=0, width=2)
    mask = Image.new("L", im.size, 0)
    ImageDraw.Draw(mask).rectangle([x0 + 300, int(0.40 * PAGE_H), x1 - 200, int(0.52 * PAGE_H)], fill=255)
    im.paste(hatch, (0, 0), mask)
    for i in range(5):
        ax = x0 + 60 + i * 15
        d.line([(ax, y0 + 120 + i * 200), (ax + 240, y0 + 40 + i * 200)], fill=0, width=3)
        d.polygon([(ax + 240, y0 + 40 + i * 200), (ax + 215, y0 + 45 + i * 200), (ax + 228, y0 + 62 + i * 200)], fill=0)
    d.line([(x1 - 120, y0 + 30), (x1 - 120, int(0.70 * PAGE_H))], fill=0, width=7)
    for i, txt in enumerate(["NEW FLUE TO", "TERMINATE ABOVE", "PARAPET"]):
        txt_im = Image.new("L", (520, 40), 255)
        ImageDraw.Draw(txt_im).text((0, 0), txt, fill=0, font=font(28))
        im.paste(txt_im.rotate(90, expand=True), (x1 - 100 + i * 34, y0 + 300))
    tb = (int(0.24 * PAGE_W), int(0.735 * PAGE_H), int(0.72 * PAGE_W), int(0.835 * PAGE_H))
    d.rectangle(tb, outline=0, width=3)
    d.text((tb[0] + 330, tb[1] + 10), "*Approved*", fill=0, font=font(30))
    d.text((tb[0] + 20, tb[1] + 105), "Planner", fill=0, font=font(26))
    d.text((tb[0] + 480, tb[1] + 105), "Date  10/19/09", fill=0, font=font(28))
    sl, st, sr, sb = (int(SIGNATURE[0] * PAGE_W), int(SIGNATURE[1] * PAGE_H),
                      int(SIGNATURE[2] * PAGE_W), int(SIGNATURE[3] * PAGE_H))
    draw_signature(d, (sl, st, sr, sb), rng)
    d.text((int(0.18 * PAGE_W), int(0.88 * PAGE_H)), "TOWER RETROFIT PROJECT", fill=0, font=font(64))
    d.text((int(0.36 * PAGE_W), int(0.93 * PAGE_H)), "901 SW EXAMPLE AVE.", fill=0, font=font(40))
    return im


def make_page(path):
    draw_page().convert("RGB").save(path, "PDF", resolution=DPI)


RAW = []
PICTURE_MERGES = []


def record_raw_clusters():
    """Instrumentation only: read LayoutPostprocessor's input and its picture-overlap step."""
    orig = lpp.LayoutPostprocessor.__init__
    orig_remove = lpp.LayoutPostprocessor._remove_overlapping_clusters

    def init(self, page, clusters, options):
        RAW.append((page.size, [c.model_copy() for c in clusters]))
        orig(self, page, clusters, options)

    def remove(self, clusters, cluster_type, *args, **kwargs):
        kept = orig_remove(self, clusters, cluster_type, *args, **kwargs)
        if cluster_type == "picture":
            kept_ids = {c.id for c in kept}
            PICTURE_MERGES.append([c for c in clusters if c.id not in kept_ids])
        return kept

    lpp.LayoutPostprocessor.__init__ = init
    lpp.LayoutPostprocessor._remove_overlapping_clusters = remove


def converter(score_threshold=None):
    opts = PdfPipelineOptions(do_picture_classification=True)
    opts.accelerator_options = AcceleratorOptions(device=AcceleratorDevice.CPU, num_threads=4)
    if score_threshold is not None:
        layout = LayoutObjectDetectionOptions()
        layout.engine_options.score_threshold = score_threshold
        opts.layout_options = layout
    return DocumentConverter(format_options={InputFormat.PDF: PdfFormatOption(pipeline_options=opts)})


def fractions(bbox, size):
    return tuple(round(v, 3) for v in (bbox.l / size.width, bbox.t / size.height, bbox.r / size.width, bbox.b / size.height))


def inside_fraction(bbox, size, region):
    l, t, r, b = fractions(bbox, size)
    iw = max(0.0, min(r, region[2]) - max(l, region[0]))
    ih = max(0.0, min(b, region[3]) - max(t, region[1]))
    return (iw * ih) / max(1e-9, (r - l) * (b - t)), (iw * ih) / ((region[2] - region[0]) * (region[3] - region[1]))


def part4():
    page = Page(page_no=1, size=Size(width=1000, height=1000))
    def c(i, box, conf):
        return Cluster(id=i, label=DocItemLabel.PICTURE, confidence=conf,
                       bbox=BoundingBox(l=box[0], t=box[1], r=box[2], b=box[3], coord_origin=CoordOrigin.TOPLEFT))
    clusters = [c(0, (50, 50, 900, 900), 0.95), c(1, (300, 780, 480, 830), 0.90)]
    out = lpp.LayoutPostprocessor(page, clusters, LayoutPostprocessorOptions()).postprocess()
    return [(k.id, k.label.value) for k in out]


def main():
    out_dir = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(tempfile.mkdtemp())
    out_dir.mkdir(parents=True, exist_ok=True)
    pdf = out_dir / "nested_picture.pdf"
    make_page(pdf)
    print(f"docling: {dpc.__file__}")
    print(f"input: {pdf}")

    record_raw_clusters()
    captured = {}
    orig_prepare = dpc.DocumentPictureClassifier.prepare_element

    def prepare(self, conv_res, element):
        el = orig_prepare(self, conv_res, element)
        if el is not None and "tight" not in captured:
            page = conv_res.pages[0]
            w, h = page.size.width, page.size.height
            box = BoundingBox(l=SIGNATURE[0] * w, t=SIGNATURE[1] * h, r=SIGNATURE[2] * w, b=SIGNATURE[3] * h,
                              coord_origin=CoordOrigin.TOPLEFT)
            captured["tight"] = page.get_image(scale=self.images_scale, cropbox=box)
            captured["whole"] = el.image
            captured["model"] = self
        return el

    dpc.DocumentPictureClassifier.prepare_element = prepare

    res = converter().convert(pdf)
    raw_default = list(RAW)
    merged_default = [c for group in PICTURE_MERGES for c in group]
    print("\nPart 1: PictureItems in the output (default pipeline + do_picture_classification)")
    for item, _ in res.document.iterate_items():
        if isinstance(item, PictureItem):
            size = res.document.pages[item.prov[0].page_no].size
            bb = item.prov[0].bbox.to_top_left_origin(size.height)
            top = item.meta.classification.predictions[0]
            print(f"  {item.self_ref} bbox(frac)={fractions(bb, size)} -> {top.class_name} {top.confidence:.3f}")
    print(f"  classifier input for the picture: {captured['whole'].size} px")

    print("\nPart 2: same classifier on a tight crop of the signature")
    from docling.datamodel.base_models import ItemAndImageEnrichmentElement
    probe = PictureItem(self_ref="#/pictures/999", label=DocItemLabel.PICTURE)
    captured["tight"].save(out_dir / "signature_crop.png")
    list(captured["model"](res.document, [ItemAndImageEnrichmentElement(item=probe, image=captured["tight"])]))
    preds = probe.meta.classification.predictions[:3]
    print(f"  crop {captured['tight'].size} px -> " + ", ".join(f"{p.class_name} {p.confidence:.3f}" for p in preds))

    print("\nPart 3: raw layout clusters (before LayoutPostprocessor) mostly inside the signature box")
    for label, thr in (("default engine score_threshold (0.3)", None), ("score_threshold 0.01", 0.01)):
        RAW.clear()
        if thr is None:
            RAW.extend(raw_default)
        else:
            converter(thr).convert(pdf)
        size, clusters = RAW[0]
        hits = []
        for k in clusters:
            own, cov = inside_fraction(k.bbox, size, SIGNATURE)
            if own > 0.5 and cov > 0.5:
                hits.append(f"{k.label.value}@{k.confidence:.3f}")
        print(f"  {label}: {len(clusters)} raw clusters; on the signature: {hits or 'none'}")
    size = raw_default[0][0]
    dropped = [f"{c.label.value}@{c.confidence:.3f} {fractions(c.bbox, size)}" for c in merged_default]
    print("  default run, pictures removed by LayoutPostprocessor._remove_overlapping_clusters('picture'):")
    print(f"    {dropped or 'none'}")

    print("\nPart 4: no model, hand-built clusters through LayoutPostprocessor")
    print("  input : outer picture (50,50,900,900) conf 0.95 + inner picture (300,780,480,830) conf 0.90")
    print(f"  output: {part4()}")



if __name__ == "__main__":
    main()

Output (the same on 2.152.0 and on main; paths shortened):

docling: <site-packages>/docling/models/stages/picture_classifier/document_picture_classifier.py
input: <OUT_DIR>/nested_picture.pdf

Part 1: PictureItems in the output (default pipeline + do_picture_classification)
  #/pictures/0 bbox(frac)=(0.059, 0.059, 0.924, 0.86) -> engineering_drawing 0.914
  classifier input for the picture: (1058, 1269) px

Part 2: same classifier on a tight crop of the signature
  crop (208, 63) px -> signature 0.994, icon 0.001, engineering_drawing 0.001

Part 3: raw layout clusters (before LayoutPostprocessor) mostly inside the signature box
  default engine score_threshold (0.3): 16 raw clusters; on the signature: ['[email protected]']
  score_threshold 0.01: 300 raw clusters; on the signature: ['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]']
  default run, pictures removed by LayoutPostprocessor._remove_overlapping_clusters('picture'):
    ['[email protected] (0.252, 0.756, 0.481, 0.811)']

Part 4: no model, hand-built clusters through LayoutPostprocessor
  input : outer picture (50,50,900,900) conf 0.95 + inner picture (300,780,480,830) conf 0.90
  output: [(0, 'picture')]

Found, reproduced and drafted with an AI coding agent (Claude Code); reviewed before filing.

Dominant language
Python
Stars
71k
Forks
5.4k
Avg merge
2d 22h
Merged PRs (30d)
161

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from docling-project/docling

All issues in docling-project/docling

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.