npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

bgustreadimg

v0.1.4

Published

Adaptive image preprocessing engine for OCR pipelines — Sauvola binarization in O(N) with Rust

Readme

bgustreadimg 🖼️


💡 La Visión

bgustreadimg es un motor de preprocesamiento de imágenes de nivel industrial construido desde cero en Rust. Está diseñado para eliminar el ruido visual en fotografías de documentos —facturas, contratos, capturas de cámara— antes de ser enviadas a motores de OCR. A diferencia de los convertidores de formato convencionales, su núcleo implementa Binarización Adaptativa de Sauvola con Imágenes Integrales (SAT) para lograr una limpieza uniforme en tiempo lineal O(N), independientemente del tamaño de la ventana de análisis local.


🌟 Características Clave

  • Binarización Adaptativa Sauvola O(N): Umbral de contraste local dinámico usando Summed Area Tables. Elimina sombras, arrugas y fondos no uniformes sin distorsionar los caracteres.
  • Redimensionamiento Inteligente con Lanczos3: Escalado de alta calidad que conserva la nitidez del texto. Selección automática del ancho objetivo basada en la memoria RAM disponible.
  • Detección de Layout Opcional (ONNX): Módulo LayoutAnalyzer basado en Table Transformer para extraer regiones tabulares de documentos escaneados.
  • Inferencia OCR Opcional (ONNX): Módulo OcrEngine basado en Surya OCR para reconocimiento de texto multilingüe end-to-end.
  • Bindings NAPI-RS Nativos: Extensión dinámica .node cargada directamente por Node.js sin sobrecoste de IPC ni dependencias Python.
  • Doble Canal de Distribución: Biblioteca estática (rlib) para Rust en crates.io y bindings dinámicos (cdylib) para npm.

🏗️ Arquitectura del Pipeline

                    ┌─────────────────────┐
                    │   Input Image       │
                    │  (JPEG, PNG, ...)   │
                    └─────────┬───────────┘
                              │
                    ┌─────────▼───────────┐
                    │  Metadata Probe     │
                    │  (formato, dims)    │  ── sin decodificar a RAM
                    └─────────┬───────────┘
                              │
                    ┌─────────▼───────────┐
                    │  Decode & Resize    │
                    │  Lanczos3, auto-RAM │
                    └─────────┬───────────┘
                              │
                    ┌─────────▼───────────┐
                    │  Sauvola Adaptive   │
                    │  Binarization (SAT) │
                    │  O(N), window_size  │
                    └─────────┬───────────┘
                              │
                    ┌─────────▼───────────┐
                    │  Layout Detection   │  ── ONNX (table-transformer)
                    │  (opcional)         │
                    └─────────┬───────────┘
                              │
                    ┌─────────▼───────────┐
                    │  OCR Inference      │  ── ONNX (surya-ocr)
                    │  (opcional)         │
                    └─────────┬───────────┘
                              │
                    ┌─────────▼───────────┐
                    │  Clean Output PNG   │
                    │  (sin pérdidas)     │
                    └─────────────────────┘

📦 Canales de Distribución

1. Canal Rust (Crates.io) 🦀

  • Versión Activa: v0.1.4
  • Tipo: Biblioteca estática (rlib).
  • Uso:
    [dependencies]
    bgustreadimg = "0.1.4"

2. Canal Node.js & NPM 🟢

  • Versión Activa: v0.1.4
  • Tipo: Extensión nativa (cdylib mediante NAPI-RS).
  • Instalación:
    npm install bgustreadimg

🛠️ Instalación y Compilación de Desarrollo

  1. Clonar el repositorio:

    git clone https://github.com/B-GUST/bgustreadimg.git
    cd bgustreadimg
  2. Compilar la librería Rust:

    cargo build --release
  3. Compilar bindings de Node.js (opcional):

    npm install
    npm run build

🚀 Primeros Pasos

Rust

use bgustreadimg::preprocess_image_rs;

let image_data = std::fs::read("input.jpg").unwrap();
let result = preprocess_image_rs(image_data, Some(
    bgustreadimg::PreprocessConfigRs {
        window_size: Some(25),
        k: Some(0.2),
        target_width: Some(1920),
    }
)).await.unwrap();

std::fs::write("output.png", result).unwrap();

Node.js

const { preprocessImage } = require('bgustreadimg');
const fs = require('fs');

const clean = await preprocessImage(fs.readFileSync('input.jpg'), {
    windowSize: 25,
    k: 0.2,
    targetWidth: 1920,
});
fs.writeFileSync('output.png', clean);

⚙️ Configuración

| Parámetro | Default | Descripción | |---------------|---------|-------------| | windowSize | 25 | Tamaño de la ventana local de análisis (impar, ≥3) | | k | 0.2 | Sensibilidad al contraste (menor = más agresivo con sombras) | | targetWidth | auto | Ancho máximo de salida; auto-selecciona 1920 o 1280 según RAM libre |


🧩 Estructura del Proyecto

├── Cargo.toml          # Manifiesto Rust (publicable en crates.io)
├── build.rs            # Script de compilación NAPI-RS
├── src/
│   ├── lib.rs          # Núcleo: Sauvola threshold, preprocess_image, bindings NAPI
│   ├── layout.rs       # LayoutAnalyzer — detección de tablas con ONNX
│   └── ocr.rs          # OcrEngine — reconocimiento de texto con ONNX
├── index.js            # Binding NAPI-RS para Node.js (auto-generado)
├── index.d.ts          # Declaraciones de tipos TypeScript
├── models/             # Modelos ONNX (gitignored, descarga bajo demanda)
│   ├── sury-ocr/
│   └── table-transformer/
├── package.json        # Manifiesto npm
├── CONTRIBUTING.md     # Guía de contribución
├── CREDITS.md          # Créditos y atribuciones
└── LICENSE             # Licencia MIT

📜 Licencia y Créditos

Este proyecto se distribuye bajo la licencia MIT. Consulta el archivo CREDITS.md para atribuciones al algoritmo de Sauvola y las librerías de terceros.