### Install Dependencies and Start Example Source: https://github.com/gutenye/ocr/blob/main/packages/browser/example/README.md Run these commands in your terminal to install project dependencies and start the example browser. ```bash cd ../.. && bun install cd browser/example bun install ./ake start ``` -------------------------------- ### Install Dependencies and Run Example Source: https://github.com/gutenye/ocr/blob/main/packages/node/example/README.md Follow these commands to install project dependencies, navigate to the Node.js example directory, install its specific dependencies, and then run the example with a sample image. ```bash cd ../.. && bun install cd examples/node bun install ./ake start assets/cn-01.jpg ``` -------------------------------- ### Getting Started with C++ OCR Project Source: https://github.com/gutenye/ocr/blob/main/packages/react-native/cpp/example/README.md Follow these steps to download dependencies and start the C++ OCR project. Ensure you have the necessary tools installed. ```sh Download onnxruntime from https://github.com/microsoft/onnxruntime/releases brew install opencv ./ake start ``` -------------------------------- ### Install OCR Browser Package Source: https://context7.com/gutenye/ocr/llms.txt Provides commands for installing the Gutenye OCR package for browser environments using Bun. ```sh # Browser bun add @gutenye/ocr-browser ``` -------------------------------- ### Install Git LFS and Clone Repository Source: https://github.com/gutenye/ocr/blob/main/README.md Instructions for installing Git Large File Storage (LFS) and cloning the Guten OCR repository. ```sh brew install git-lfs git clone git@github.com:gutenye/ocr.git ``` -------------------------------- ### Install and Use Guten OCR in Node.js Source: https://github.com/gutenye/ocr/blob/main/README.md Install the Node.js package and create an OCR instance to detect text in an image. ```typescript bun add @gutenye/ocr-node import Ocr from '@gutenye/ocr-node' const ocr = await Ocr.create() const result = await ocr.detect('a.jpg') ``` -------------------------------- ### Install and Use Guten OCR in Browser Source: https://github.com/gutenye/ocr/blob/main/README.md Install the Browser package and initialize OCR with model paths. Detect text in an image using the provided path. ```typescript bun add @gutenye/ocr-browser import Ocr from '@gutenye/ocr-browser' const ocr = await Ocr.create({ models: { detectionPath: '/assets/ch_PP-OCRv4_det_infer.onnx', recognitionPath: '/assets/ch_PP-OCRv4_rec_infer.onnx', dictionaryPath: '/assets/ppocr_keys_v1.txt' } }) const result = await ocr.detect('/a.jpg') ``` -------------------------------- ### Install OCR Node.js Package Source: https://context7.com/gutenye/ocr/llms.txt Provides commands for installing the Gutenye OCR package for Node.js environments using Bun or npm. ```sh # Node.js bun add @gutenye/ocr-node # or: npm install @gutenye/ocr-node ``` -------------------------------- ### Native C++ OCR Build Prerequisites Source: https://context7.com/gutenye/ocr/llms.txt Lists prerequisites for building the native C++ OCR library, including installing OpenCV via Homebrew and downloading ONNX Runtime. ```sh # Prerequisites brew install opencv # Download onnxruntime from https://github.com/microsoft/onnxruntime/releases ./ake start ``` -------------------------------- ### Install and Use Guten OCR in React Native Source: https://github.com/gutenye/ocr/blob/main/README.md Install the React Native package and create an OCR instance for text detection. ```typescript bun add @gutenye/ocr-react-native import Ocr from '@gutenye/ocr-react-native' const ocr = await Ocr.create() const result = await ocr.detect('a.jpg') ``` -------------------------------- ### Install OCR React Native/Expo Package Source: https://context7.com/gutenye/ocr/llms.txt Provides commands for installing the Gutenye OCR package for React Native and Expo projects using Bun. ```sh # React Native / Expo bun add @gutenye/ocr-react-native ``` -------------------------------- ### Detect Text from Raw Pixel Buffer (Node.js) Source: https://context7.com/gutenye/ocr/llms.txt Perform OCR on raw pixel data obtained from an image. This method is useful when you have image data in memory, for example, after processing with libraries like `sharp`. ONNX options can be passed for fine-tuning. ```typescript // --- Node.js: detect from raw pixel buffer --- import fs from 'node:fs/promises' import sharp from 'sharp' const { data, info } = await sharp('./assets/en-01.jpg') .raw() .toBuffer({ resolveWithObject: true }) const result = await ocr.detect( { data, width: info.width, height: info.height }, { onnxOptions: { logSeverityLevel: 3 } } // Node.js only ) ``` -------------------------------- ### Initialize and Use Guten OCR in C++ Source: https://github.com/gutenye/ocr/blob/main/README.md Include the native OCR header, create a NativeOcr instance, and detect text in an image. ```cpp #include "native-ocr.h" NativeOcr* ocr = new NativeOcr(..) auto result = ocr->detect("a.jpg"); ``` -------------------------------- ### Ocr.create() Source: https://github.com/gutenye/ocr/blob/main/README.md Initializes the OCR instance with optional configuration. Supports different models and debugging options. ```APIDOC ## Ocr.create() ### Description Initializes the OCR instance with optional configuration. Supports different models and debugging options. ### Method `Ocr.create(options?: { models?: { detectionPath: string, recognitionPath: string, dictionaryPath: string }, isDebug?: boolean, debugOutputDir?: string, recognitionImageMaxSize?: number, detectionThreshold?: number, detectionBoxThreshold?: number, detectionUnclipRatiop?: number, detectionUseDilate?: boolean, detectionUsePolygonScore?: boolean, useDirectionClassify?: boolean, onnxOptions?: {} }): Promise ### Parameters #### Options - **models** (object) - Optional - Configuration for OCR models. - **detectionPath** (string) - Path to the detection model. - **recognitionPath** (string) - Path to the recognition model. - **dictionaryPath** (string) - Path to the dictionary file. - **isDebug** (boolean) - Optional - Enables debug mode. - **debugOutputDir** (string) - Optional - Directory for debug output (Node.js only). - **recognitionImageMaxSize** (number) - Optional - Maximum size for recognition images (React Native only). - **detectionThreshold** (number) - Optional - Threshold for detection (React Native only). - **detectionBoxThreshold** (number) - Optional - Threshold for detection boxes (React Native only). - **detectionUnclipRatiop** (number) - Optional - Unclip ratio for detection (React Native only). - **detectionUseDilate** (boolean) - Optional - Whether to use dilation for detection (React Native only). - **detectionUsePolygonScore** (boolean) - Optional - Whether to use polygon scores for detection (React Native only). - **useDirectionClassify** (boolean) - Optional - Whether to use direction classification. - **onnxOptions** (object) - Optional - Options to pass to ONNX Runtime. ### Returns A Promise that resolves to an Ocr instance. ``` -------------------------------- ### Ocr.create(options?) Source: https://context7.com/gutenye/ocr/llms.txt Initializes an OCR instance by loading the necessary ONNX models. This method can be used with default bundled models or with custom model paths and options. ```APIDOC ## Ocr.create(options?) ### Description Creates and returns an `Ocr` instance by loading ONNX detection and recognition models into memory. For Node.js and React Native, bundled model paths are used by default; the Browser package requires explicit paths to hosted model assets. ### Method `Ocr.create(options?)` ### Parameters #### Options - **models** (object) - Optional - Paths to the ONNX detection, recognition, and dictionary models. - **detectionPath** (string) - Path to the detection model. - **recognitionPath** (string) - Path to the recognition model. - **dictionaryPath** (string) - Path to the dictionary file. - **isDebug** (boolean) - Optional - If true, saves intermediate images for debugging. - **debugOutputDir** (string) - Optional - Directory for debug images (Node.js only). - **onnxOptions** (object) - Optional - Options passed directly to ONNX Runtime session (Node.js only). - **logSeverityLevel** (number) - Logging level for ONNX Runtime. ### Request Example ```javascript // Minimal (Node.js / React Native — uses bundled models automatically) const ocr = await Ocr.create() // With all options (Node.js) const ocr = await Ocr.create({ models: { detectionPath: '/path/to/ch_PP-OCRv4_det_infer.onnx', recognitionPath: '/path/to/ch_PP-OCRv4_rec_infer.onnx', dictionaryPath: '/path/to/ppocr_keys_v1.txt', }, isDebug: true, debugOutputDir: './output', onnxOptions: { logSeverityLevel: 3, }, }) // Browser — model paths must point to publicly served assets const ocrBrowser = await Ocr.create({ models: { detectionPath: '/assets/ch_PP-OCRv4_det_infer.onnx', recognitionPath: '/assets/ch_PP-OCRv4_rec_infer.onnx', dictionaryPath: '/assets/ppocr_keys_v1.txt', }, isDebug: true, }) ``` ### Response - **Ocr** - An initialized OCR instance. ``` -------------------------------- ### Guten OCR API Reference - Create Instance Source: https://github.com/gutenye/ocr/blob/main/README.md Configuration options for creating an OCR instance, including model paths and debugging settings. Some options are platform-specific. ```typescript Ocr.create({ models?: { detectionPath: string recognitionPath: string dictionaryPath: string }, isDebug?: boolean debugOutputDir?: string // Node only recognitionImageMaxSize?: number // RN only detectionThreshold?: number // RN only detectionBoxThreshold?: number // RN only detectionUnclipRatiop?: number // RN only detectionUseDilate?: boolean // RN only detectionUsePolygonScore?: boolean // RN only useDirectionClassify?: boolean // RN only onnxOptions?: {} // Node only. Pass to ONNX Runtime }): Promise ``` -------------------------------- ### Initialize OCR Instance Source: https://context7.com/gutenye/ocr/llms.txt Use `Ocr.create()` to load models. For Node.js/React Native, bundled models are used by default. Browser environments require explicit paths to hosted model assets. ```typescript import Ocr from '@gutenye/ocr-node' // or '@gutenye/ocr-browser' / '@gutenye/ocr-react-native' // Minimal (Node.js / React Native — uses bundled models automatically) const ocr = await Ocr.create() // With all options (Node.js) const ocr = await Ocr.create({ // Override bundled model paths (all three required if overriding) models: { detectionPath: '/path/to/ch_PP-OCRv4_det_infer.onnx', recognitionPath: '/path/to/ch_PP-OCRv4_rec_infer.onnx', dictionaryPath: '/path/to/ppocr_keys_v1.txt', }, isDebug: true, // Save intermediate images for debugging debugOutputDir: './output', // Directory for debug images (Node.js only) onnxOptions: { // Passed directly to ONNX Runtime session (Node.js only) logSeverityLevel: 3, }, }) // Browser — model paths must point to publicly served assets const ocrBrowser = await Ocr.create({ models: { detectionPath: '/assets/ch_PP-OCRv4_det_infer.onnx', recognitionPath: '/assets/ch_PP-OCRv4_rec_infer.onnx', dictionaryPath: '/assets/ppocr_keys_v1.txt', }, isDebug: true, }) ``` -------------------------------- ### Find Required Packages Source: https://github.com/gutenye/ocr/blob/main/packages/react-native/android/CMakeLists.txt Locates and loads the necessary OpenCV and ReactAndroid packages for the project. ```cmake find_package(OpenCV REQUIRED) find_package(ReactAndroid REQUIRED CONFIG) ``` -------------------------------- ### Define Executable and Link Libraries Source: https://github.com/gutenye/ocr/blob/main/packages/react-native/cpp/example/CMakeLists.txt Creates an executable target named 'ocr' using specified source files and links it with the ONNX Runtime and OpenCV libraries. Ensure the ONNX Runtime library path is correct for your system. ```cmake file(GLOB SOURCES "../*.cpp") add_executable(${PROJECT_NAME} cpp-example.cpp ${SOURCES}) target_link_libraries(${PROJECT_NAME} PRIVATE ${CMAKE_SOURCE_DIR}/onnxruntime/lib/libonnxruntime.dylib ${OpenCV_LIBS} ) ``` -------------------------------- ### Configure C++ Standard and Verbose Build Source: https://github.com/gutenye/ocr/blob/main/packages/react-native/android/CMakeLists.txt Enables verbose build output and sets the C++ standard to C++23, ensuring it's required. ```cmake set(CMAKE_VERBOSE_MAKEFILE ON) set(CMAKE_CXX_STANDARD 23) set(CMAKE_CXX_STANDARD_REQUIRED True) ``` -------------------------------- ### registerBackend Source: https://context7.com/gutenye/ocr/llms.txt Enables the integration of custom platform-specific implementations for core OCR functionalities. This is useful for advanced use cases or integrating Guten OCR into custom runtimes. ```APIDOC ## registerBackend ### Description Allows injecting platform-specific implementations of `FileUtils`, `ImageRaw`, `InferenceSession`, and `splitIntoLineImages` into the common core. ### Method `registerBackend(backend: object) ### Parameters #### Backend Object - **FileUtils** (object) - Must implement: `static read(path: string): Promise`. - **ImageRaw** (object) - Must extend `ImageRawBase` and implement: `open`, `resize`, `drawBox`, `write`. - **InferenceSession** (object) - ONNX Runtime `InferenceSession` constructor. - **splitIntoLineImages** (function) - Contour-detection function using OpenCV. - **defaultModels** (object) - Optional - Object containing paths to custom models. - **detectionPath** (string) - Path to the detection model. - **recognitionPath** (string) - Path to the recognition model. - **dictionaryPath** (string) - Path to the dictionary file. ### Request Example ```ts import { registerBackend } from '@gutenye/ocr-common' import { InferenceSession } from 'onnxruntime-node' import { FileUtils } from './MyFileUtils' import { ImageRaw } from './MyImageRaw' import { splitIntoLineImages } from '@gutenye/ocr-common/splitIntoLineImages' registerBackend({ FileUtils, ImageRaw, InferenceSession, splitIntoLineImages, defaultModels: { detectionPath: '/custom/det.onnx', recognitionPath: '/custom/rec.onnx', dictionaryPath: '/custom/keys.txt', }, }) // After registration, use the standard Ocr API import { Ocr } from '@gutenye/ocr-common' const ocr = await Ocr.create() const result = await ocr.detect('image.jpg') ``` ``` -------------------------------- ### Troubleshooting C++ OCR Project Dependencies Source: https://github.com/gutenye/ocr/blob/main/packages/react-native/cpp/example/README.md Common issues and their solutions for the C++ OCR project. Reinstalling dependencies can resolve missing library errors. ```sh - libavcodec.60.dylib not found: brew reinstall ffmpeg@6 - OpenCV not found: brew resinstall opencv ``` -------------------------------- ### Configure C++ Standard and Project Source: https://github.com/gutenye/ocr/blob/main/packages/react-native/cpp/example/CMakeLists.txt Sets the minimum required CMake version, defines the project name and version, and specifies the C++ standard to be used (C++23). ```cmake cmake_minimum_required(VERSION 3.10) project(ocr VERSION 1.0.0) set(CMAKE_CXX_STANDARD 23) set(CMAKE_CXX_STANDARD_REQUIRED True) ``` -------------------------------- ### Copy Assets for React Native Project Source: https://github.com/gutenye/ocr/blob/main/docs/React Native.md Use this command to copy assets into the resources directory for your React Native project. Ensure you are in the correct package directory. ```bash cd packages/react-native cp -rL ../../assets resources ``` -------------------------------- ### Ocr.create Source: https://context7.com/gutenye/ocr/llms.txt Initializes the OCR engine, allowing for fine-tuning with React Native specific parameters. These parameters control aspects like image size limits, detection sensitivity, and the use of text direction classification. ```APIDOC ## Ocr.create ### Description Initializes the OCR engine with optional React Native specific parameters for fine-tuning. ### Method `Ocr.create(options?: object) ### Parameters #### Options - **recognitionImageMaxSize** (number) - Optional - Max dimension for recognition crops. - **detectionThreshold** (number) - Optional - Probability threshold for text pixel detection. - **detectionBoxThreshold** (number) - Optional - Threshold for text box scoring. - **detectionUnclipRatiop** (number) - Optional - Expansion ratio for detected boxes. - **detectionUseDilate** (boolean) - Optional - Apply dilation to detection output. - **detectionUsePolygonScore** (boolean) - Optional - Use polygon vs box scoring. - **useDirectionClassify** (boolean) - Optional - Enable text direction classification. ### Request Example ```ts import Ocr from '@gutenye/ocr-react-native' const ocr = await Ocr.create({ recognitionImageMaxSize: 320, detectionThreshold: 0.3, detectionBoxThreshold: 0.6, detectionUnclipRatiop: 1.5, detectionUseDilate: false, detectionUsePolygonScore: false, useDirectionClassify: true, }) const result = await ocr.detect('file:///path/to/image.jpg') result.texts.forEach(line => console.log(line.text)) ``` ``` -------------------------------- ### ocr.detect(image, options?) Source: https://context7.com/gutenye/ocr/llms.txt Runs the full OCR pipeline on an image to detect and recognize text lines. It accepts image data in various formats and returns structured results. ```APIDOC ## ocr.detect(image, options?) ### Description Runs the full OCR pipeline (detection → crop → recognition) on the given image and returns an array of recognized text lines with bounding boxes and confidence scores. Accepts either a file path string or raw pixel data. ### Method `ocr.detect(image, options?) ### Parameters #### Image Input - **image** (string | object) - The image to process. Can be a file path (string) or raw pixel data (object). - If object: `{ data: Buffer, width: number, height: number }` #### Options - **onnxOptions** (object) - Optional - Options passed directly to ONNX Runtime session (Node.js only). - **logSeverityLevel** (number) - Logging level for ONNX Runtime. ### Request Example ```javascript // --- Node.js: detect from file path --- const result = await ocr.detect('./assets/cn-01.jpg') console.log(result.resizedImageWidth) console.log(result.resizedImageHeight) for (const line of result.texts) { console.log(`[${line.mean.toFixed(2)}] ${line.text}`) // line.box: [[x1,y1],[x2,y2],[x3,y3],[x4,y4]] } // --- Node.js: detect from raw pixel buffer --- import fs from 'node:fs/promises' import sharp from 'sharp' const { data, info } = await sharp('./assets/en-01.jpg') .raw() .toBuffer({ resolveWithObject: true }) const result = await ocr.detect( { data, width: info.width, height: info.height }, { onnxOptions: { logSeverityLevel: 3 } } // Node.js only ) // --- Browser: detect from an object URL or image URL --- const file = document.querySelector('#input-image').files[0] const imageUrl = URL.createObjectURL(file) const result = await ocr.detect(imageUrl) const startTime = Date.now() const browserResult = await ocr.detect('/assets/en-01.jpg') console.log(`OCR took ${Date.now() - startTime}ms`) browserResult.texts.forEach(line => { console.log(`${line.mean.toFixed(2)}: ${line.text}`) }) ``` ### Response - **resizedImageWidth** (number) - The width of the image after resizing for the OCR models. - **resizedImageHeight** (number) - The height of the image after resizing for the OCR models. - **texts** (array) - An array of detected text lines. - **text** (string) - The recognized text. - **mean** (number) - The mean confidence score for the text line. - **box** (array) - The bounding box coordinates of the text line: `[[x1,y1],[x2,y2],[x3,y3],[x4,y4]]`. ``` -------------------------------- ### Glob Source Files Source: https://github.com/gutenye/ocr/blob/main/packages/react-native/android/CMakeLists.txt Finds all .cpp files in the current directory and a 'cpp' subdirectory for compilation. ```cmake file(GLOB SOURCES "./*.cpp" "../cpp/*.cpp") ``` -------------------------------- ### Include Directories Source: https://github.com/gutenye/ocr/blob/main/packages/react-native/android/CMakeLists.txt Adds necessary include directories for C++ compilation, including custom headers and libraries. ```cmake include_directories( ../cpp ${OpenCV_INCLUDE_DIRS} ${CMAKE_SOURCE_DIR}/build/onnxruntime/headers ) ``` -------------------------------- ### Find and Include Packages Source: https://github.com/gutenye/ocr/blob/main/packages/react-native/cpp/example/CMakeLists.txt Locates the OpenCV package and makes its include directories available for the project. This is necessary to use OpenCV functionalities. ```cmake find_package(OpenCV REQUIRED) include_directories( ${CMAKE_SOURCE_DIR}/.. ${CMAKE_SOURCE_DIR}/onnxruntime/include ${OpenCV_INCLUDE_DIRS} ) ``` -------------------------------- ### Configure OCR for React Native Source: https://context7.com/gutenye/ocr/llms.txt Initializes the OCR engine with fine-tuning parameters for detection sensitivity and image preprocessing. Detects text from a specified image file. ```typescript import Ocr from '@gutenye/ocr-react-native' const ocr = await Ocr.create({ recognitionImageMaxSize: 320, // Max dimension for recognition crops (default varies) detectionThreshold: 0.3, // Probability threshold for text pixel detection detectionBoxThreshold: 0.6, // Threshold for text box scoring detectionUnclipRatiop: 1.5, // Expansion ratio for detected boxes detectionUseDilate: false, // Apply dilation to detection output detectionUsePolygonScore: false, // Use polygon vs box scoring useDirectionClassify: true, // Enable text direction classification }) const result = await ocr.detect('file:///path/to/image.jpg') result.texts.forEach(line => console.log(line.text)) ``` -------------------------------- ### Set CMake Minimum Version and Project Name Source: https://github.com/gutenye/ocr/blob/main/packages/react-native/android/CMakeLists.txt Specifies the minimum required CMake version and defines the project name. ```cmake cmake_minimum_required(VERSION 3.10) project(guten-ocr) ``` -------------------------------- ### Specify OpenCV Directory Source: https://github.com/gutenye/ocr/blob/main/packages/react-native/android/CMakeLists.txt Sets the directory for OpenCV mobile SDK, crucial for OpenCV-dependent builds. ```cmake set(OpenCV_DIR "${CMAKE_SOURCE_DIR}/build/opencv-mobile-4.9.0-android/sdk/native/jni") ``` -------------------------------- ### Detect Text from Image File Path (Node.js) Source: https://context7.com/gutenye/ocr/llms.txt Run the full OCR pipeline on an image specified by its file path. The result includes resized image dimensions and an array of recognized text lines with bounding boxes and confidence scores. ```typescript // --- Node.js: detect from file path --- const result = await ocr.detect('./assets/cn-01.jpg') console.log(result.resizedImageWidth) // e.g. 640 console.log(result.resizedImageHeight) // e.g. 480 for (const line of result.texts) { console.log(`[${line.mean.toFixed(2)}] ${line.text}`) // e.g. "[0.97] Hello World" // line.box: [[x1,y1],[x2,y2],[x3,y3],[x4,y4]] — four corner points } ``` -------------------------------- ### Register Custom Backend for OCR Source: https://context7.com/gutenye/ocr/llms.txt Injects platform-specific implementations for file utilities, image handling, inference sessions, and line image splitting. Allows integration into custom runtimes. ```typescript import { registerBackend } from '@gutenye/ocr-common' import { InferenceSession } from 'onnxruntime-node' import { FileUtils } from './MyFileUtils' import { ImageRaw } from './MyImageRaw' import { splitIntoLineImages } from '@gutenye/ocr-common/splitIntoLineImages' registerBackend({ FileUtils, ImageRaw, InferenceSession, splitIntoLineImages, defaultModels: { detectionPath: '/custom/det.onnx', recognitionPath: '/custom/rec.onnx', dictionaryPath: '/custom/keys.txt', }, }) // After registration, use the standard Ocr API import { Ocr } from '@gutenye/ocr-common' const ocr = await Ocr.create() const result = await ocr.detect('image.jpg') ``` -------------------------------- ### Link Libraries Source: https://github.com/gutenye/ocr/blob/main/packages/react-native/android/CMakeLists.txt Links the project's shared library with OpenCV, ONNX Runtime, and React Native JSI/JNI libraries. ```cmake target_link_libraries( ${PROJECT_NAME} ${OpenCV_LIBS} ${CMAKE_SOURCE_DIR}/build/onnxruntime/jni/${CMAKE_ANDROID_ARCH_ABI}/libonnxruntime.so ReactAndroid::jsi ReactAndroid::reactnativejni ) ``` -------------------------------- ### ocr.detect() Source: https://github.com/gutenye/ocr/blob/main/README.md Performs OCR detection on the given image. ```APIDOC ## ocr.detect() ### Description Performs OCR detection on the given image. ### Method `ocr.detect(image: string | {data: Uint8Array | Uint8ClampedArray | Buffer, width: number, height: number}, options?: { onnxOptions?: {} }): Promise<{texts: TextLine[], resizedImageWidth: number, resizedImageHeight: number}> ### Parameters #### image - **image** (string | object) - Required - The image to process. Can be a path (string) or an object with image data. - **data** (Uint8Array | Uint8ClampedArray | Buffer) - The image data. - **width** (number) - The width of the image. - **height** (number) - The height of the image. #### options - **onnxOptions** (object) - Optional - Options to pass to ONNX Runtime (Node.js only). ### Returns A Promise that resolves to an object containing detected texts and resized image dimensions. #### TextLine Object - **text** (string) - The recognized text. - **score** (number) - The confidence score of the recognition. - **frame** (object) - The bounding box of the text. - **top** (number) - **left** (number) - **width** (number) - **height** (number) ``` -------------------------------- ### Native C++ OCR Detection Source: https://context7.com/gutenye/ocr/llms.txt Performs OCR detection using native C++ components with ONNX Runtime and OpenCV. Requires specifying paths to model files and the character dictionary. ```cpp #include "native-ocr.h" #include int main() { // Construct with paths to ONNX model files and character dictionary NativeOcr* ocr = new NativeOcr( "models/ch_PP-OCRv4_det_infer.onnx", "models/ch_PP-OCRv4_rec_infer.onnx", "models/ppocr_keys_v1.txt" ); auto result = ocr->detect("input.jpg"); for (const auto& line : result) { std::cout << line.text << " (score: " << line.score << ")" << std::endl; } delete ocr; return 0; } ``` -------------------------------- ### Detect Text from Image URL (Browser) Source: https://context7.com/gutenye/ocr/llms.txt In browser environments, OCR can be performed on images loaded from URLs, such as those from file inputs or directly from web URLs. The `ocr.detect` method accepts a URL string. ```typescript // --- Browser: detect from an object URL or image URL --- const file = document.querySelector('#input-image').files[0] const imageUrl = URL.createObjectURL(file) const result = await ocr.detect(imageUrl) const startTime = Date.now() const browserResult = await ocr.detect('/assets/en-01.jpg') console.log(`OCR took ${Date.now() - startTime}ms`) browserResult.texts.forEach(line => { console.log(`${line.mean.toFixed(2)}: ${line.text}`) }) ``` -------------------------------- ### Add Shared Library Target Source: https://github.com/gutenye/ocr/blob/main/packages/react-native/android/CMakeLists.txt Defines a shared library target named after the project, including all discovered source files. ```cmake add_library( ${PROJECT_NAME} SHARED ${SOURCES} ) ``` -------------------------------- ### Guten OCR API Reference - Detect Text Source: https://github.com/gutenye/ocr/blob/main/README.md Method to detect text in an image, accepting either a file path or image data with dimensions. Returns detected texts and image dimensions. ```typescript ocr.detect(imagePath: string | {data: Uint8Array | Uint8ClampedArray | Buffer, width: number, height: number}, { onnxOptions?: {} // Node only. Pass to ONNX Runtime }): Promise<{texts: TextLine[], resizedImageWidth: number, resizedImageHeight: number}> ``` -------------------------------- ### NativeOcr::detect Source: https://context7.com/gutenye/ocr/llms.txt Performs text detection on an input image using the native C++ OCR engine. This method is part of the standalone C++ library. ```APIDOC ## NativeOcr::detect ### Description Detects text in an image using the native C++ OCR engine. ### Method `NativeOcr::detect(const std::string& imagePath): std::vector ### Parameters #### Path Parameters - **imagePath** (string) - Required - Path to the input image file. ### Response #### Success Response - **std::vector** - A vector of TextLine objects, each containing detected text, score, and bounding box. ### Request Example ```cpp #include "native-ocr.h" #include int main() { NativeOcr* ocr = new NativeOcr( "models/ch_PP-OCRv4_det_infer.onnx", "models/ch_PP-OCRv4_rec_infer.onnx", "models/ppocr_keys_v1.txt" ); auto result = ocr->detect("input.jpg"); for (const auto& line : result) { std::cout << line.text << " (score: " << line.score << ")" << std::endl; } delete ocr; return 0; } ``` ``` -------------------------------- ### Pretty-print TextLine results in TypeScript Source: https://context7.com/gutenye/ocr/llms.txt Iterates through detected text lines, extracting text, confidence score, and bounding box coordinates. Filters out lines with a confidence score below 0.5. ```typescript type TextLine = { text: string // Recognized text string mean: number // Confidence score 0–1 (lines with mean < 0.5 are filtered out) box?: number[][] // Four corner points [[x1,y1],[x2,y2],[x3,y3],[x4,y4]] } // Example usage — pretty-print results const result = await ocr.detect('receipt.jpg') result.texts.forEach((line, i) => { const { text, mean, box } = line const [topLeft, topRight, bottomRight, bottomLeft] = box ?? [] console.log(`Line ${i}: "${text}" (confidence: ${(mean * 100).toFixed(1)}%)`) if (topLeft) { console.log(` Position: (${topLeft[0]}, ${topLeft[1]}) → (${bottomRight[0]}, ${bottomRight[1]})`) } }) ``` -------------------------------- ### Guten OCR API Reference - TextLine Structure Source: https://github.com/gutenye/ocr/blob/main/README.md Defines the structure of a detected text line, including the text content, confidence score, and bounding box coordinates. ```typescript TextLine { text: string score: number frame: { top, left, width, height } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.