Skip to main content

bgustreadimg 🖼️

Motor de Preprocesamiento de Imágenes Adaptativo de Alto Rendimiento para Pipelines de OCR.
Elimina sombras, arrugas y variaciones de luz no uniformes en milisegundos — 100% Rust nativo.

Crates Version NPM Version Stable Version License


💡 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.
  • 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.
  • Multiplataforma: Bindings para Node.js (NAPI-RS), Python (PyO3) y WebAssembly (wasm-bindgen) desde el mismo núcleo Rust.

🏗️ 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  │
                    └─────────┬───────────┘
                              │
                    ┌─────────▼───────────┐
                    │  Clean Output PNG   │
                    │  (sin pérdidas)     │
                    └─────────────────────┘

📦 Canales de Distribución

1. Canal Rust (Crates.io) 🦀

  • Tipo: Biblioteca estática (rlib).
  • Uso:
    [dependencies]
    bgustreadimg = "0.2.1"
    

2. Canal Node.js & NPM (Backend) 🟢

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

3. Canal Python & Pip (Maturin) 🐍

  • Tipo: Módulo nativo compilado (PyO3).
  • Instalación:
    pip install bgustreadimg
    

4. Canal Frontend & NPM (WebAssembly) 🌐

  • Tipo: Paquete JS/WASM para navegador (wasm-bindgen).
  • Instalación:
    npm install bgustreadimg-wasm
    

🛠️ Instalación y Compilación de Desarrollo

  1. Clonar el repositorio:

    git clone https://github.com/B-GUST/bgustreadimg.git
    cd bgustreadimg
    
  2. Compilar para Node.js (NAPI-RS):

    npm install
    npm run build
    
  3. Compilar para Python (Maturin):

    # Requiere instalar maturin
    pip install maturin
    PYO3_USE_ABI3_FORWARD_COMPATIBILITY=1 maturin build --release
    
  4. Compilar para Frontend/Navegador (WASM):

    # Compila a WASM y prepara el paquete listo para npm en pkg-wasm/
    npm run build:wasm
    

🚀 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 (Backend)

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);

Python

import bgustreadimg

with open("input.jpg", "rb") as f:
    data = f.read()

config = bgustreadimg.PreprocessConfigPy(window_size=25, k=0.2, target_width=1920)
clean = bgustreadimg.preprocess_image(data, config)

with open("output.png", "wb") as f:
    f.write(clean)

Frontend (Navegador/WASM)

import init, { preprocessImage } from 'bgustreadimg-wasm';

await init(); // Inicializar módulo WASM

const fileBuffer = await file.arrayBuffer();
const cleanBuffer = preprocessImage(new Uint8Array(fileBuffer), 25, 0.2, 1280);

⚙️ 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)
├── pyproject.toml      # Manifiesto Python (publicable con maturin)
├── package.json        # Manifiesto npm
├── build.rs            # Script de compilación condicional
├── scripts/
│   └── prepare-wasm-pkg.js # Script de post-procesamiento para WASM
├── docs/
│   ├── README_WASM.md  # README del paquete frontend/WASM
│   ├── updated_multi_platform_plan.md # Plan de arquitectura multi-plataforma
│   └── implementation_report.md # Reporte de cambios realizados
├── src/
│   ├── lib.rs          # Núcleo: Sauvola threshold, preprocess_image_sync
│   ├── bindings_napi.rs # Bindings específicos para Node.js
│   ├── bindings_pyo3.rs # Bindings específicos para Python
│   └── bindings_wasm.rs # Bindings específicos para WebAssembly
├── index.js            # Binding NAPI-RS para Node.js (auto-generado)
├── index.d.ts          # Declaraciones de tipos TypeScript para Node.js
└── 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.

Release files for bgustreadimg 0.2.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for bgustreadimg 0.2.1
File Size Uploaded
bgustreadimg-0.2.1.tar.gz 17.2 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for bgustreadimg 0.2.1
File Interpreter ABI Platform
bgustreadimg-0.2.1-cp314-cp314-manylinux_2_34_x86_64.whl CPython 3.14 CPython 3.14 Linux glibc 2.34+ x86-64 Details

Total release size: 502.8 kB

Release files / bgustreadimg-0.2.1.tar.gz

Download URL bgustreadimg-0.2.1.tar.gz
Size 17.2 kB
Tags Source
SHA-256 checksum
How to use checksums
b97c3450a5469b24d8334faca426bea57967a1625ef26a884a3752043d8c422c
BLAKE2b-256 checksum
How to use checksums
045566a1380709659e9cb3169bada312c5a3ff84feef1f23cdd3b09978d1f60b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.7

Release files / bgustreadimg-0.2.1-cp314-cp314-manylinux_2_34_x86_64.whl

Download URL bgustreadimg-0.2.1-cp314-cp314-manylinux_2_34_x86_64.whl
Size 485.7 kB
Tags CPython 3.14 Linux glibc 2.34+ x86-64
SHA-256 checksum
How to use checksums
45942b7c31ec42becb0a6920077789ca79f957a8f7d77ccff3eb288bbb051d3f
BLAKE2b-256 checksum
How to use checksums
71731133b9fbb552cb7ae28f63bf6f2b1aa0b6392d4f1671dbd13c5cda1705cc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.7

Release history Release notifications | RSS feed

0.3.0

1 release file

This release

0.2.1 This release

2 release files

0.1.5

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page