---
title: "Extract key-value pairs from an image in C#"
url: https://recursiveai.org/oneocr/cookbook/extract-key-value-pairs-from-image/
description: "Read labeled fields from an image with OneOcr in C#. Get key and value word indices, keep their locations, and run the downloadable example."
version: "1.0.0"
---

# Extract key-value pairs from an image in C#

**OneOcr** is a free, open-source OCR library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneOcr) · [GitHub](https://github.com/recursive-ai-oss/oneocr-csharp) · [Docs](https://recursiveai.org/oneocr/docs/) · [Download example (.zip)](https://recursiveai.org/oneocr/cookbook/extract-key-value-pairs-from-image/extract-key-value-pairs-from-image.zip)

Key-value extraction connects a printed label to its value, such as “Total” and “125.00”. It is separate from reading the text itself.

```shell
dotnet add package RecursiveAI.OneOcr
dotnet add package RecursiveAI.OneOcr.Models
dotnet add package RecursiveAI.OneOcr.Models.Documents
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using OneImage;
using OneOcr;
using OneOcr.Documents;
using OneOcr.Models.Documents;

DocumentModels.Configure();
var page = Image.Load("form.png")
    .Ocr(OcrEngine.LoadBundled());
string Text(IReadOnlyList<int> indices) =>
    string.Join(" ", indices.Select(
        i => page.Words[i].Text)).TrimEnd(':');
foreach (var pair in page.FindKeyValues())
    Console.WriteLine(
        $"{Text(pair.KeyWordIndices)} = " +
        Text(pair.ValueWordIndices));
```

Unzip [the example](https://recursiveai.org/oneocr/cookbook/extract-key-value-pairs-from-image/extract-key-value-pairs-from-image.zip), then `dotnet run`.

The snippet assumes a default `dotnet new console` project with implicit usings enabled. For `form.png` in the download, prints:

```text
Date = 2026-11-16
Total = 125.00
```

OCR reads all four labels, but the extraction model returns pairs only for Date and Total on this image. It does not pair Invoice number or Customer; the API does not report a reason for each omitted label. Readable text alone does not guarantee a key-value association.

## The full program

The download includes `form.png`, an original synthetic image with this text:

```text
Invoice number: INV-1042
Date: 2026-11-16
Customer: Jane Smith
Total: 125.00
```

The full program prints the OCR text, then each returned pair and its word indices. These indices point into `page.Words`; each word also has a `Box` in image pixels.

```csharp
using OneOcr.Models.Documents;
using OneOcr.Documents;
using OneImage;
using OneOcr;
DocumentModels.Configure();
var engine = OcrEngine.LoadBundled();
var page = Image.Load("form.png").Ocr(engine);
Console.WriteLine(page.Text);
foreach (var pair in page.FindKeyValues())
{
    string key = string.Join(" ", pair.KeyWordIndices.Select(i => page.Words[i].Text)).TrimEnd(':');
    string value = string.Join(" ", pair.ValueWordIndices.Select(i => page.Words[i].Text));
    Console.WriteLine($"{key} = {value}");
    Console.WriteLine($"Key words: {string.Join(",", pair.KeyWordIndices)}; value words: {string.Join(",", pair.ValueWordIndices)}");
}
```

```text
Invoice number: INV-1042

Date: 2026-11-16

Customer: Jane Smith

Total: 125.00
Date = 2026-11-16
Key words: 3; value words: 4
Total = 125.00
Key words: 8; value words: 9
```

Call `DocumentModels.Configure()` once at startup: calling it again throws `InvalidOperationException`, and calling `FindKeyValues()` without a default extractor also throws it.

## Variations

Keep the pairs on a new page instead of just enumerating them. This replaces the loop after reading `page`:

```csharp
var paired = page.WithKeyValues();
Console.WriteLine(paired.KeyValues.Count);
Console.WriteLine(page.KeyValues.Count);
```

```text
2
0
```

## Related recipes

- [Extract text from an image](https://recursiveai.org/oneocr/cookbook/extract-text-from-image/)
- [Read OCR words and coordinates as JSON](https://recursiveai.org/oneocr/cookbook/page-json/)

## The short answer

Use `Image.Load(...).Ocr(engine)` to recognize the page, then `page.FindKeyValues()` to find label/value associations. Install both the recognition weights and the document extraction weights. They do different jobs: the recognizer reads letters; the extractor identifies and connects words already on the page.

The return value is not a dictionary of strings. Each `OcrKeyValue` carries `KeyWordIndices`, `ValueWordIndices`, a surrounding `Box`, `Confidence` and `Source`. Keeping word references lets you recover both the text and its original location without trying to match strings back onto the image. This matters when the same number or label appears several times.

## How do I extract key-value pairs from an image in C#?

Read the image into an `OcrPage` before extracting fields. The example uses the bundled recognizer and document extractor, so no external service or schema is needed. `FindKeyValues()` returns pairs in the order of their values on the page, as documented in the [extraction API](https://github.com/recursive-ai-oss/oneocr-csharp/blob/8db430fb77c4d86d51686f15dfd9b5ccc20c99a7/src/OneOcr/Documents/DocumentExtractor.cs#L155-L165).

To reconstruct a label or value, select each referenced word from `page.Words` and join its `Text`, as the full program does. Do not treat an index as a character offset. A multiword label can contain several indices, and a value can contain several words too. Keep the original page alongside the pairs for that reason.

Use `pair.Box` for the enclosing key-and-value area. Use the individual referenced words’ boxes when you need separate highlights for the label and its value. Image coordinates have a top-left origin, with y increasing downward; they are pixels, not PDF points.

### Can OCR extract every labeled field from a form?

Not necessarily. In this run OCR reads all four printed lines, but the extractor returns only Date and Total. Invoice number and Customer do not become pairs. That is a useful distinction for an application: readable text does not imply that every association was found. The program deliberately prints the recognized page before the pair list so you can see which stage omitted a field.

A missing pair should remain missing in your result, rather than being filled by guessing at a nearby word. Decide which fields your application requires and send incomplete records for review. The pair’s confidence is about the association; it is not a replacement for checking the recognized value itself.

### How do I keep key-value pairs in OCR JSON?

Call `WithKeyValues()` and serialize the returned page with [the page JSON API](https://recursiveai.org/oneocr/docs/page-json/). The original page is unchanged. Existing pairs are kept first, and newly found pairs are appended. Calling the method repeatedly is therefore not a deduplication operation. In the variation above, the new page has two pairs while the original has none.

Generic pairing is also different from extracting an invoice schema. If you need invoice business terms, line items and typed amounts, use [invoice extraction](https://recursiveai.org/oneocr/cookbook/invoices/) rather than treating generic pairs as a complete invoice parser. The pairing API preserves what it associated on the page; it does not promise all required business fields.
