Skip to contents

Agronomic trials and breeding nurseries routinely track experimental entries using physical plot stakes, barcode tags, seed packet labels, and ear tags in livestock. In pliman, image_ocr_dl() integrates deep neural text detection (DBNet / CRAFT) and text recognition (CRNN/SVTR / TrOCR) models to automatically extract text strings and their spatial coordinates directly from field imagery.

Usage

image_ocr_dl(
  img,
  det_model = c("ppocrv5_det", "ppocrv5_det_server", "ppocr_det", "ppocr_det_server",
    "craft", "trocr_small"),
  rec_model = c("ppocrv5_rec_latin", "ppocrv5_rec", "ppocrv5_rec_server", "ppocr_rec",
    "trocr_small"),
  language = c("latin", "english"),
  det_thresh = 0.3,
  box_thresh = 0.6,
  unclip_ratio = 1.5,
  text_threshold = 0.7,
  link_threshold = 0.4,
  low_text = 0.4,
  min_size = 5L,
  min_score = 0,
  sort = TRUE,
  col = "forestgreen",
  lwd = 2L,
  cex = 0.8,
  badge = TRUE,
  labels = c("text", "id", "both", "none"),
  threads = 0,
  engine = c("gpu", "cpu"),
  plot = TRUE,
  dir = pliman_model_dir(),
  verbose = TRUE,
  det_limit = NULL,
  textline_ori = TRUE,
  charset = NULL,
  rec_dict = NULL,
  rec_batch = 8L,
  keep_empty = FALSE,
  ...
)

Arguments

img

An Image object or character string path to an image file.

det_model

Text detection backbone model. Options are:

  • "ppocrv5_det": PP-OCRv5 Mobile DBNet (default, fast, printed and handwritten text).

  • "ppocrv5_det_server": PP-OCRv5 Server DBNet (highest accuracy).

  • "ppocr_det": PP-OCRv4 Mobile DBNet (legacy).

  • "ppocr_det_server": PP-OCRv4 Server DBNet (legacy).

  • "craft": Clova AI CRAFT (irregular/curved scene text).

  • "trocr_small": Alias running CRAFT detection with TrOCR Small recognition.

A path to a compatible DBNet ONNX file is also accepted.

rec_model

Text recognition backbone model:

  • "ppocrv5_rec_latin": PP-OCRv5 Latin recognition (default when language = "latin").

  • "ppocrv5_rec": PP-OCRv5 Mobile recognition (default when language = "english").

  • "ppocrv5_rec_server": PP-OCRv5 Server recognition (best for difficult handwriting).

  • "ppocr_rec": PP-OCRv4 recognition (legacy; printed text, numbers, codes).

  • "trocr_small": TrOCR Small encoder-decoder (English handwriting lines).

A path to a compatible CTC recognition ONNX file is also accepted (see rec_dict).

language

Language family used to pick the default recognizer (and the TrOCR variant): "latin" (default; Latin/Portuguese text with diacritics) or "english".

det_thresh

Pixel binarization threshold for DBNet text polygon detection (default 0.30).

box_thresh

Minimum mean probability for retaining DBNet text regions (default 0.60).

unclip_ratio

Polygon expansion ratio to prevent cropping character boundaries (DBNet models, default 1.50). Larger values (1.6–2.0) help handwriting with long ascenders/descenders.

text_threshold

Character center confidence threshold for CRAFT detector (default 0.70).

Character affinity link threshold for CRAFT detector (default 0.40).

low_text

Lower bound text score threshold for CRAFT detector (default 0.40).

min_size

Minimum text box height in pixels to filter out noise (default 5L).

min_score

Minimum recognition confidence score to retain text boxes (default 0.0).

sort

Logical. Whether to sort detected text regions in natural reading order (top-to-bottom, line-by-line, left-to-right). Default is TRUE.

col

Border color for recognized text bounding polygons (default "forestgreen").

lwd

Line width for rendering detected text polygon borders (default 2L).

cex

Character expansion factor for recognized text labels (default 0.80).

badge

Logical. Whether to render filled background badges behind transcribed text (default TRUE).

labels

Label type to display on the plot: "text" (default), "id", "both", or "none".

threads

Number of CPU execution threads (default 0 for auto-detect).

engine

Compute engine: "gpu" (default) or "cpu".

plot

Logical. Whether to render the visual OCR annotation plot (default TRUE).

dir

Model directory (default pliman_model_dir()).

verbose

Logical. Whether to show progress messages (default TRUE).

det_limit

Longest image side (pixels) used for text detection. The image is resized (up or down) to this size before detection. Default NULL uses 960 for DBNet models and 1280 for CRAFT. Increase it (e.g. 1600–2000) for very small text in large photographs.

textline_ori

Logical. Whether to run the PP-LCNet text-line orientation classifier to fix upside-down crops (default TRUE). Ignored for TrOCR.

charset

Optional allow-list of characters for CTC recognizers, either as a plain string of characters (e.g. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-") or as a regular-expression bracket expression (e.g. "[0-9A-Z-]"). Default NULL (no restriction).

rec_dict

Optional path to the character dictionary (one character per line) of a custom CTC recognition model. Default NULL uses the dictionary that matches rec_model.

rec_batch

Number of text crops recognized per inference batch (default 8L).

keep_empty

Logical. Whether to keep detected regions in which no character was recognized (default FALSE).

...

Additional arguments passed to graphics::plot().

Value

A data.frame of class c("pliman_ocr", "data.frame") containing:

  • id: Sequential text region identifier.

  • line: Visual text line index (when sort = TRUE).

  • text: Transcribed character string.

  • score: Recognition confidence score (0 to 1).

  • det_score: Detection confidence score.

  • xmin, ymin, xmax, ymax: Axis-aligned bounding box coordinates.

  • x1, y1, ..., x4, y4: Corners (top-left, top-right, bottom-right, bottom-left) of the rotated text quadrilateral.

  • angle: Text direction angle in degrees.

With attributes "image" (original image) and "timing" (seconds spent in each stage).

Details

The OCR pipeline operates in modular stages:

  1. Text Detection (det_model): Identifies oriented text regions on the image. The image is first resized so that its longest side equals det_limit (the scale the detectors were trained on), which is both faster and more accurate than running on full-resolution photographs.

    • "ppocrv5_det": PP-OCRv5 Mobile DBNet (default, ~4.8 MB). Trained with printed and handwritten text; fast and accurate for labels, tags and notes.

    • "ppocrv5_det_server": PP-OCRv5 Server DBNet (~88 MB). Highest detection quality for dense or difficult handwriting, distant plot markers, or cluttered backgrounds.

    • "ppocr_det": PP-OCRv4 Mobile DBNet (~4.7 MB, legacy).

    • "ppocr_det_server": PP-OCRv4 Server DBNet (~113 MB, legacy).

    • "craft": Clova AI CRAFT (Character Region Awareness for Text Detection, ~80 MB). Uses dual Gaussian heatmaps (character center score + inter-character affinity link). Useful for irregular or curved scene text.

    • "trocr_small": Shortcut convenience alias. Automatically pairs the "craft" detector with the TrOCR recognition model.

    Each detected region is returned as a rotated quadrilateral (columns x1..y4), so tilted handwriting is rectified before recognition instead of being cropped together with neighbouring lines.

  2. Text-line orientation (textline_ori): A tiny PP-LCNet classifier (~1 MB) detects upside-down (180 degrees) text crops and flips them before recognition.

  3. Text Recognition (rec_model): Transcribes cropped image patches into character strings. Crops are rendered at 48 px height with their native aspect ratio (dynamic width, so long lines are not squeezed) and processed in batches of rec_batch.

    • "ppocrv5_rec": PP-OCRv5 Mobile recognition (~16 MB). Single model for printed and handwritten Chinese, English, and Latin-script text.

    • "ppocrv5_rec_server": PP-OCRv5 Server recognition (~85 MB). Best accuracy on handwriting; slower.

    • "ppocrv5_rec_latin": PP-OCRv5 Latin Mobile recognition (~8 MB). Covers Latin-script languages with diacritics (e.g., Portuguese "\u00e7", "\u00e3", "\u00e9").

    • "ppocr_rec": PP-OCRv4 SVTR/LCNet model (~12 MB, legacy). Optimized for printed typography and alphanumeric entry codes.

    • "trocr_small": Microsoft TrOCR Small (encoder + autoregressive RoBERTa decoder). Transformer-based model trained on English handwritten text lines (IAM); it tends to hallucinate words on field photographs and short codes.

    When rec_model is not supplied, language = "latin" selects "ppocrv5_rec_latin" and language = "english" selects "ppocrv5_rec".

Restricting the character set: For plot stakes and seed packets the set of possible characters is often known (e.g. only capital letters, digits, and hyphens). Supplying charset (e.g. "[0-9A-Z-]" or "0123456789G") masks every other character during CTC decoding, which removes confusions such as "G196" being read as "6196" or "Gi96".

Reading Order Sorting: When sort = TRUE (the default), detected boxes are organized using spatial vertical IoU line-clustering (> 0.35 overlap threshold) to group words belonging to the same text line, followed by left-to-right sorting within each line, reproducing natural human reading order.

Hardware: on GPUs, ONNX Runtime may need a warm-up call per new input shape. Speed gains from engine = "gpu" depend on a compatible CUDA device; on small images the CPU engine can be equally fast.

S3 Methods: The returned object of class "pliman_ocr" supports:

  • print(x): Displays a clean tabular summary with line assignments and coordinates.

  • plot(x): Renders the annotated image with colored (rotated) boxes and badges.

  • as.character(x): Returns the complete transcribed text with newline ("\n") breaks.

References

  • Liao, M., Wan, Z., Yao, C., Chen, K., & Bai, X. (2020). Real-time scene text detection with differentiable binarization. Proceedings of the AAAI Conference on Artificial Intelligence, 34(07), 11474–11481.

  • Du, Y., Li, C., Guo, R., Yin, X., Liu, W., Zhou, J., ... & Hu, B. (2020). PP-OCR: A practical ultra lightweight OCR system. arXiv preprint arXiv:2009.09941.

  • Cui, C., Sun, T., Lin, M., et al. (2025). PaddleOCR 3.0 Technical Report. arXiv preprint arXiv:2507.05595.

  • Baek, Y., Lee, B., Han, D., Yun, S., & Lee, H. (2019). Character region awareness for text detection. Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR), 9365–9374.

  • Li, M., Lv, T., Chen, J., Cui, L., Lu, Y., Florencio, D., Zhang, C., & Wei, F. (2023). TrOCR: Transformer-based optical character recognition with pre-trained models. AAAI Conference on Human Computation and Crowdsourcing.

Examples

if (FALSE) { # interactive()
  library(pliman)
  img <- image_import("flaxtext")
  # Default: PP-OCRv5 detection + Latin recognition
  ocr_res <- image_ocr_dl(img)
  print(ocr_res)

  # Difficult handwriting: server models
  ocr_hw <- image_ocr_dl(img, det_model = "ppocrv5_det_server", rec_model = "ppocrv5_rec_server")

  # Seed packet codes: restrict the alphabet
  ocr_code <- image_ocr_dl(img, charset = "[0-9A-Z-]")

  # Convert to plain text string with line breaks
  cat(as.character(ocr_res))
}