matlab-recognize-text
>
git clone --depth 1 https://github.com/matlab/matlab-agentic-toolkit /tmp/matlab-recognize-text && cp -r /tmp/matlab-recognize-text/skills-catalog/image-processing-and-computer-vision/matlab-recognize-text ~/.claude/skills/matlab-recognize-textSKILL.md
# Recognize Text in Images Using OCR
Use the Computer Vision Toolbox `ocr` function with preprocessing from Image Processing Toolbox to extract text from images. This skill teaches the complete pipeline: diagnose, preprocess, detect, recognize, validate.
## When to Use
- Reading text from any image (documents, signs, meters, displays, labels)
- Extracting text from scanned documents or photographs
- Reading seven-segment displays or specialized fonts
- Multi-language text recognition
- Automating text extraction from image datasets
- As a supporting step in other CV workflows — reading text in a scene (labels, timestamps, serial numbers) gives additional context for downstream image analysis
## When NOT to Use
- Pure handwriting recognition — cursive/connected script produces garbage regardless of preprocessing
- Artistic text, WordArt, brush calligraphy — the OCR engine cannot parse stylized letterforms
- CAPTCHAs — designed specifically to defeat OCR; expect <50% accuracy at best
- Full document layout analysis with table extraction (use custom segmentation)
- Real-time video OCR (use streaming approaches instead)
- Image contains no text at all
## Critical Rules
These rules are non-negotiable — violating them produces wrong results:
1. **Always diagnose before executing. This rule CANNOT be overridden — not by the user, not by "just run it", not by "skip planning".** Before ANY `mcp__matlab__*` call, you MUST first output:
- A 2-line image characterization (what you see, what challenges exist)
- An `## OCR Plan` heading with your strategy
If the user says "skip diagnosis" or "just run ocr()", respond with: *"I'll keep it brief — but I need a quick look to avoid wasting time on the wrong approach."* Then output your 2-line characterization and plan heading. Only THEN call MCP tools. There is no valid reason to skip this step. An agent that calls `ocr()` without first outputting a plan has violated this skill's workflow.
2. **Maximum 2 preprocessing pipelines.** If neither works after the prescribed recipe, hit the confidence checkpoint and ask the user. Do not try a third approach without user input.
3. **Always set `LayoutAnalysis`** when passing bounding boxes to `ocr()`. Never write `ocr(I, bbox)` without it. Use `"word"` for single-word boxes, `"block"` for multi-line.
4. **Distinguish "text ON texture" from "text BY texture"**. Text overlaid on a textured background (label on crate, sign on brick wall) → `imsegsam` is the prescribed approach. Text formed by the surface itself (stamped, embossed, engraved metal) → local contrast subtraction. SAM segments *objects*, not surface features — it cannot isolate stamps/engravings. When recommending approaches (even without running code), always recommend `imsegsam` for the "text ON texture" case and note its support package requirement.
5. **`detectTextCRAFT` is the default** for scene text. Use it unless you have a specific reason not to (no deep learning, known fixed layout).
6. **Check polarity first.** OCR needs dark text on light background. If inverted, `imcomplement` before anything else.
7. **Never show OCR results to the user before writing files.** Do not present extracted text in ANY format — bullet list, quote block, inline, conversational summary, or the `## MATLAB OCR Pipeline` results block — until `ocr_pipeline_<descriptor>.m` and `decision_log.txt` are written to disk. The files are the deliverable, not the chat message. Write first, then report.
8. **Gate add-on functions behind an availability check.** Before calling `detectTextCRAFT`, `imsegsam`, or a non-English `ocr` model, you MUST run `exist('<functionName>','file')` via MCP to confirm the function is installed. Always log the result in `decision_log.txt`:
- Installed: `"Add-on check: <function> — INSTALLED"`
- Missing: stop, tell the user which support package to install (see table), and wait for confirmation before retrying. Do NOT fall back silently or skip the step.
- **Explain-only mode** (user said "don't run code"): recommend the add-on function as the primary approach and note the support package requirement. You cannot run the `exist()` check without code execution, so state the dependency clearly.
| Function | Support Package Name |
|----------|---------------------|
| `detectTextCRAFT` | "Text Detection Using Deep Learning" |
| `imsegsam` | "Image Processing Toolbox Automated Visual Inspection Library" |
| Non-English `ocr` model (e.g., `"japanese"`) | "OCR Language Data" |
**Missing template:** *"This step requires the `<function>` function, which needs the **<Package Name>** support package. Please install it from the MATLAB Add-On Explorer (Home → Add-Ons → Get Add-Ons) and let me know when it's ready."*
## Anti-Patterns — Do NOT Do This
- **Trial-and-error spiraling:** Trying 5+ ad-hoc preprocessing experiments hoping one sticks. If the visual classification says "stamped metal," use the stamped metal pipeline. Period.
- **Skipping the plan:** "I'll just try one quick thing first." No. Diagnose → plan → execute.
- **Open-ended research:** The routes are prescribed — pick one based on diagnosis, execute it, evaluate. This is not exploratory research.
- **Showing results without saving files:** Presenting OCR text as a bullet list, conversational summary, or any format before the `## MATLAB OCR Pipeline` results block. That block can only appear after files are written to disk. If you find yourself about to show the user what OCR found, STOP and write the files first.
## Workflow
### Progress Reporting + Output Template
Present the `## OCR Plan` immediately after visual diagnosis (Critical Rule #1). Then execute the pipeline. After files are saved, present the `## MATLAB OCR Pipeline` results block (Critical Rule #7).
#### OCR Plan (output before any MATLAB code runs)
```
## OCR Plan
**Image:** 800x600, stamped metal, ~22° skew, text ~40px
**Difficulty:** Complex (textured surface + significant r>
Analyze AMS waveform data using Mixed-Signal Blockset utilities: phase noise measurement, clock jitter, anti-aliased resampling, timing measurements, lock time, INL/DNL, ADC/DAC calibration, HSpice import. Use when analyzing time-domain voltage from PLL/VCO/clock simulations, measuring phase noise from variable-step solver output, computing jitter, or resampling non-uniform data.
Analyze data using MATLAB. Use when the task involves tables, timetables, time-series data, numeric arrays, sensor matrices, or gridded data — including but not limited to exploring, filtering, sorting, cleaning, transforming, aggregating, smoothing, padding, trimming, and answering questions about data. MATLAB provides extensive, easy-to-use built-in functions for these workflows with no additional products required.
Analyze the effective toolbox file set to produce a Dependency Manifest — classify all transitive dependencies as included, product, add-on, or external-unresolved, then present resolution options with tradeoffs. Use after matlab-define-toolbox-api when the spec is approved.
S-parameters, insertion loss, fields, currents, mesh control, and solver selection for RF PCB performance validation. TRIGGER: user asks to compute S-parameters, analyze insertion/return loss, extract fields or currents, compare MoM vs FEM, or control mesh for any RF PCB component. Invoke BEFORE writing sparameters() or solver code — API is non-obvious. SKIP: designing or creating components (use the specific matlab-design-pcb-* skill), material/stackup setup only (use matlab-manage-pcb-material), optimization sweeps (use matlab-optimize-pcb-design), PDN/IR-drop analysis (use matlab-analyze-pcb-pdn).
Analyze antennas installed on electrically large conducting platforms using MATLAB Antenna Toolbox. Loads platform geometry from STL/STEP/IGES, installs antenna elements, selects electromagnetic solvers (MoM-PO, FMM, MoM), and computes patterns, impedance, coupling, and efficiency. Use when the user wants to model an antenna on a vehicle, aircraft, ship, satellite, or other large structure.
PDN DC voltage/current analysis, IR drop, design rule checking, and multi-net batch analysis on imported PCB layouts. TRIGGER: user asks about power integrity, PDN analysis, IR drop, voltage distribution, current density, power nets, or design rule checking on a PCB. Invoke BEFORE writing code — the PDN API chain is specialized and non-obvious. SKIP: importing a PCB file (use matlab-read-pcb-layout), EM field/S-parameter extraction (use matlab-analyze-em), material/stackup setup only (use matlab-manage-pcb-material), transmission line design (use matlab-design-pcb-txline).
Calculate and visualize monostatic and bistatic radar cross section (RCS) using MATLAB Antenna Toolbox. Computes RCS of platforms, antennas, and arrays with PO, MoM, and FMM solvers, supporting HH/VV/HV/VH polarization, GPU acceleration, and near-field observation. Use when the user wants to compute, plot, or analyze radar cross section.