- 源码 316 文件收编为 rusto-rs/ 文件夹,随本仓库管理 - 移除内部 .git(补丁已存档 docs/rusto-rs-metal-patch-20260912.patch,上游可随时 re-clone) - target/ 与 docs/.yarn 缓存不入库;本地改动:ROCR_* 环境变量调优 + Metal 链接修复 + 预处理测试脚本
8.2 KiB
8.2 KiB
title, description, navigation, seo
| title | description | navigation | seo | ||||||
|---|---|---|---|---|---|---|---|---|---|
| Quick Start | Run your first OCR detection with RustO! across all supported platforms in under 5 minutes. |
|
|
Get up and running with RustO! across different languages with these concise, copy-pasteable examples.
Sample Document Image
Assume we have an input receipt image receipt.jpg:
┌────────────────────────────────────────┐
│ COFFEE SHOP │
│ 2026-08-20 12:30 │
│ │
│ Item Qty Price │
│ ────────────────────────────────────── │
│ Espresso Double 1 $4.50 │
│ Croissant 2 $7.00 │
│ Flat White 1 $5.00 │
│ ────────────────────────────────────── │
│ Total $16.50 │
└────────────────────────────────────────┘
1. Rust
use rusto::{
DetectTextResult, ImageSource, InitializeConfig, OcrRunOptions,
OutputGranularity, RustO,
};
fn main() -> Result<(), Box<dyn std::error::Error>> {
// 1. Initialize engine with PP-OCRv6 default preset
let config = InitializeConfig::ppv6("models/det.mnn", "models/rec.mnn", "models/dict.txt");
let mut ocr = RustO::initialize(config)?;
// 2. Run structured line OCR
let image = ImageSource::Path("receipt.jpg".into());
let mut options = OcrRunOptions::default();
options.output = OutputGranularity::Lines;
let result = ocr.detect_text(&image, &options)?;
match result {
DetectTextResult::Structured(lines) => {
println!("--- Structured Line Results ({} lines) ---", lines.len());
for line in lines {
println!(
"[{:5.1}, {:5.1}, {:5.1}, {:5.1}] (Score: {:.2}) {}",
line.frame.left, line.frame.top, line.frame.width, line.frame.height,
line.score, line.text
);
}
}
DetectTextResult::Spatial(text) => println!("{text}"),
}
// 3. Run spatial layout reconstruction OCR
options.output = OutputGranularity::Spatial;
options.line_y_threshold = Some(0.5);
options.word_x_threshold = Some(0.4);
if let DetectTextResult::Spatial(spatial_text) = ocr.detect_text(&image, &options)? {
println!("\n--- Reconstructed Spatial Layout ---\n{spatial_text}");
}
Ok(())
}
Expected Output
--- Structured Line Results (7 lines) ---
[ 95.0, 30.0, 180.0, 25.0] (Score: 0.99) COFFEE SHOP
[ 40.0, 70.0, 100.0, 20.0] (Score: 0.98) 2026-08-20
[260.0, 70.0, 60.0, 20.0] (Score: 0.97) 12:30
[ 40.0, 110.0, 280.0, 20.0] (Score: 0.96) Item Qty Price
[ 40.0, 145.0, 280.0, 20.0] (Score: 0.98) Espresso Double 1 $4.50
[ 40.0, 175.0, 280.0, 20.0] (Score: 0.97) Croissant 2 $7.00
[ 40.0, 205.0, 280.0, 20.0] (Score: 0.98) Flat White 1 $5.00
[ 40.0, 245.0, 280.0, 20.0] (Score: 0.99) Total $16.50
--- Reconstructed Spatial Layout ---
COFFEE SHOP
2026-08-20 12:30
Item Qty Price
Espresso Double 1 $4.50
Croissant 2 $7.00
Flat White 1 $5.00
Total $16.50
2. .NET / C#
using System;
using RustODotnet;
// 1. Initialize engine (loads bundled PP-OCRv6 models automatically)
using var ocr = RustO.Initialize();
// 2. Structured line detection
var imageSource = new UriImageSource("receipt.jpg");
var options = new OcrRunOptions { Output = OutputGranularity.Lines };
var result = ocr.DetectText(imageSource, options);
if (result is StructuredDetectTextResult structured)
{
foreach (var item in structured.Items)
{
Console.WriteLine($"[{item.Frame.Left:F0}, {item.Frame.Top:F0}] ({item.Score:P0}) {item.Text}");
}
}
// 3. Spatial text reconstruction
var spatialOptions = new OcrRunOptions { Output = OutputGranularity.Spatial };
var spatialResult = ocr.DetectText(imageSource, spatialOptions);
if (spatialResult is SpatialDetectTextResult spatial)
{
Console.WriteLine("\n--- Spatial Layout ---");
Console.WriteLine(spatial.Text);
}
3. React Native
import React, { useEffect, useState } from 'react';
import { Button, SafeAreaView, ScrollView, Text, View } from 'react-native';
import { detectText, initialize, TextResult } from 'react-native-rusto';
export default function QuickScanApp() {
const [lines, setLines] = useState<TextResult[]>([]);
const [spatialText, setSpatialText] = useState<string>('');
useEffect(() => {
// Initialize bundled models once at startup
initialize();
}, []);
const handleScanStructured = async () => {
const results = await detectText(
{ uri: 'file:///path/to/receipt.jpg' },
{ output: 'lines' }
);
setLines(results as TextResult[]);
};
const handleScanSpatial = async () => {
const text = await detectText(
{ uri: 'file:///path/to/receipt.jpg' },
{ output: 'spatial', lineYThreshold: 0.5, wordXThreshold: 0.4 }
);
setSpatialText(text as string);
};
return (
<SafeAreaView style={{ flex: 1, padding: 16 }}>
<Button title="Scan Lines" onPress={handleScanStructured} />
<Button title="Scan Spatial Layout" onPress={handleScanSpatial} />
<ScrollView style={{ marginTop: 16 }}>
{spatialText ? (
<Text style={{ fontFamily: 'monospace' }}>{spatialText}</Text>
) : (
lines.map((line, idx) => (
<Text key={idx}>{line.text} ({Math.round(line.score * 100)}%)</Text>
))
)}
</ScrollView>
</SafeAreaView>
);
}
4. iOS (Swift)
import Foundation
import RustO
func runQuickOcr() {
do {
// Initialize bundled models
let ocr = try RustO.initialize()
// Structured detection
let structuredResult = try ocr.detectText(.uri("receipt.jpg"), options: OcrRunOptions(output: .lines))
if case .structured(let items) = structuredResult {
for item in items {
print("[\(item.frame.left), \(item.frame.top)] (\(item.score)) \(item.text)")
}
}
// Spatial layout detection
let spatialResult = try ocr.detectText(.uri("receipt.jpg"), options: OcrRunOptions(output: .spatial))
if case .spatial(let text) = spatialResult {
print("\nReconstructed Document:\n\(text)")
}
} catch {
print("OCR Error: \(error)")
}
}
5. Android (Kotlin)
package com.example.ocr
import android.content.Context
import com.byrizki.rusto.*
fun processReceipt(context: Context, imageUri: String) {
// Automatically extracts bundled models from AAR assets
RustO.initialize(context).use { ocr ->
val source = ImageSource.Uri(imageUri)
// 1. Structured Lines
val structured = ocr.detectText(source, OcrRunOptions(output = OutputGranularity.LINES))
if (structured is DetectTextResult.Structured) {
structured.items.forEach { line ->
println("${line.text} (Score: ${line.score})")
}
}
// 2. Spatial Layout
val spatial = ocr.detectText(source, OcrRunOptions(output = OutputGranularity.SPATIAL))
if (spatial is DetectTextResult.Spatial) {
println("Spatial Layout:\n${spatial.text}")
}
}
}
6. Command Line Interface (CLI)
# 1. Output structured JSON with bounding polygon vertices
rusto --det-model det.mnn --rec-model rec.mnn --dict dict.txt --format json receipt.jpg
# 2. Output formatted spatial text layout
rusto --det-model det.mnn --rec-model rec.mnn --dict dict.txt --format text-ordered receipt.jpg
# 3. Output tab-separated values (TSV)
rusto --det-model det.mnn --rec-model rec.mnn --dict dict.txt --format tsv receipt.jpg