Metadata-Version: 2.4
Name: dotcode-decoder
Version: 1.0.1
Summary: Fast DotCode 2D barcode decoder
Author: Anish karki
Author-email: Anish karki <anishkarki989@gmail.com>
Project-URL: Homepage, https://github.com/Anish-karki/dotcode-decode
Project-URL: Repository, https://github.com/Anish-karki/dotcode-decode
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.7
Description-Content-Type: text/markdown
Requires-Dist: opencv-python>=4.5.0
Requires-Dist: numpy>=1.19.0
Requires-Dist: scipy>=1.7.0
Dynamic: author
Dynamic: requires-python

# DotCode Decoder

![Sample decode](images/dot_code_0.jpg)

![PyPI Version](https://img.shields.io/pypi/v/dotcode-decoder)
![Python Versions](https://img.shields.io/pypi/pyversions/dotcode-decoder)
![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)
![Downloads](https://img.shields.io/pypi/dm/dotcode-decoder)

**Fast, accurate DotCode 2D barcode decoder for industrial and commercial applications.(10\*47-grid)**

DotCode Decoder is a pure Python/OpenCV library for reading DotCode symbols from photos of dot-peened, laser-etched, or printed parts — built for production-line conditions where lighting is inconsistent and marks vary in clarity.

## Table of contents

- [Features](#features)
- [Installation](#installation)
- [Quick start](#quick-start)
- [API reference](#api-reference)
- [Advanced configuration](#advanced-configuration)
- [Performance](#performance)
- [How it works](#how-it-works)
- [Algorithm details](#algorithm-details)
- [Requirements](#requirements)
- [Contributing](#contributing)
- [License](#license)
- [References](#references)
- [Acknowledgments](#acknowledgments)

## Features

- Sub-50ms average decode time on real-world industrial images
- ~95%+ decode success rate out of the box
- Iterative per-row regression for skew correction, with early exit once the estimate stabilizes
- Adaptive thresholding (Otsu, fixed, and optional local/Sauvola) for uneven lighting
- Reed-Solomon error correction over GF(113)
- Configurable timeout and confidence thresholds for production tuning
- Simple one-line API for single images, plus a `DotCodeDecoder` class for full control

## Installation

```bash
pip install dotcode-decoder
```

Requires Python 3.7+. See [Requirements](#requirements) for dependency details.

## Quick start

```python
from dotcode import decode, DecodeResult

# Single image
result = decode("image.jpg")
print(result.message)  # "25E13KXUKSXG1313"

# With full details
result: DecodeResult = decode("image.jpg")
print(f"Message: {result.message}")
print(f"Time: {result.elapsed_ms:.0f}ms")
print(f"Confidence: {result.confidence:.2f}")
print(f"Method: {result.method}")
```

## API reference

### `decode()`

The simplest way to decode a DotCode image.

```python
from dotcode import decode

result = decode(
    image,                    # str (path) or np.ndarray
    target_length: int = 14,  # Fixed output length
    pad_char: str = '0',      # Padding character
    truncate: bool = True,    # Truncate if too long
    timeout_ms: int = 300,    # Max time per image
    confidence: float = 0.25, # Confidence threshold
    fast_mode: bool = True,   # Speed vs. accuracy
    use_sauvola: bool = False # Local thresholding
)
```

### `DotCodeDecoder`

For full control over decoding parameters.

```python
from dotcode import DotCodeDecoder

decoder = DotCodeDecoder(
    # Timing
    timeout_ms: int = 300,        # Max time per image (ms)

    # Quality
    confidence: float = 0.25,     # Minimum confidence (0.20-0.40)

    # Mode
    fast_mode: bool = True,       # True = faster, False = more accurate

    # Preprocessing
    use_sauvola: bool = False,    # Local thresholding for poor lighting

    # Output
    target_length: int = 14,      # Fixed output length
    pad_char: str = '0',          # Padding character
    truncate: bool = True,        # Truncate if too long
)

result = decoder.decode("image.jpg")
```

### `DecodeResult`

The result object returned by both `decode()` and `DotCodeDecoder.decode()`.

| Field        | Type          | Description                                  |
| ------------ | ------------- | -------------------------------------------- |
| `success`    | `bool`        | Whether decoding succeeded                   |
| `message`    | `str`         | Decoded text                                 |
| `confidence` | `float`       | Confidence score (0-1)                       |
| `stage`      | `DecodeStage` | `REGRESSION`, `ANGLE_SWEEP`, or `INVERT`     |
| `method`     | `str`         | Specific method used (e.g. `"reg_iter_0.0"`) |
| `elapsed_ms` | `float`       | Time taken, in milliseconds                  |
| `file`       | `str`         | Filename (batch mode)                        |
| `error`      | `str`         | Error message, if decoding failed            |
| `timed_out`  | `bool`        | Whether the timeout was hit                  |

## Advanced configuration

### Custom threshold priority

Override auto-threshold selection:

```python
decoder = DotCodeDecoder(
    fixed_threshold=155,   # Custom threshold (105-175)
    use_otsu=False         # Disable Otsu auto-threshold
)
```

### Custom angle sweep

Override the default angle sweep values:

```python
decoder = DotCodeDecoder(
    custom_angles=[1.0, 0.5, -0.5, -1.0, 2.0, -2.0]
)
```

### Fixed output length

Force exactly 14 characters:

```python
decoder = DotCodeDecoder(
    target_length=14,      # Default
    pad_char='0',          # Pad with zeros
    truncate=True          # Truncate if longer
)

# Or via decode()
result = decode("image.jpg", target_length=14)
```

## Performance

| Metric        | Value                  |
| ------------- | ---------------------- |
| Accuracy      | 95.5% (378/396 images) |
| Average speed | ~47ms per image        |
| Timeout       | 300ms (configurable)   |

### Performance by stage

| Stage           | Images    | Description                     |
| --------------- | --------- | ------------------------------- |
| Regression      | 103 (27%) | Fast path — direct grid fit     |
| Angle sweep     | 275 (73%) | Slower path — angle correction  |
| Invert fallback | 0 (0%)    | Last resort for inverted images |

## How it works

1. **Dot detection** — extracts dot centroids using adaptive thresholding (Otsu/fixed) with morphological erosion to separate touching dots.
2. **Iterative regression** — straightens tilted/skewed grids using per-row polynomial fitting, with early exit once the angle estimate stabilizes.
3. **Grid snapping** — fits detected dots to a 10×47 checkerboard grid via k-means clustering.
4. **Reed-Solomon error correction** — corrects errors in the extracted bitstream over GF(113), handling several errors per code.
5. **Text decoding** — converts corrected values to readable text using DotCode code sets (A, B, C) via a character-encoding state machine.

## Algorithm details

**Reed-Solomon error correction**

- Field: GF(113)
- Primitive element: 3
- Corrects several errors per code via the Berlekamp-Massey algorithm

**Iterative regression**

- Configurable iteration count (default: a few, with early exit)
- Early exit when angle change < 0.1°
- Per-row quadratic fit for curvature correction

**Threshold selection**

- Otsu's method (automatic)
- Fixed thresholds spanning the typical brightness range
- Optional local/Sauvola thresholding for uneven lighting

## Requirements

- Python 3.7+
- OpenCV >= 4.5.0
- NumPy >= 1.19.0
- SciPy >= 1.7.0 (for KDTree)

## Contributing

Contributions are welcome. To propose a change:

1. Open an issue describing the bug or feature before starting significant work.
2. Fork the repo and create a branch for your change.
3. Add or update tests in `test.py` covering the change.
4. Open a pull request with a clear description of what changed and why.

Please run the full test suite locally before submitting a PR.

## License

MIT License — see [LICENSE](LICENSE) for details.

## References

- [Wikipedia: DotCode](https://en.wikipedia.org/wiki/DotCode)
- [Reed-Solomon error correction](https://en.wikipedia.org/wiki/Reed%E2%80%93Solomon_error_correction)

## Acknowledgments

This project builds on research in 2D barcode decoding and industrial computer vision. Special thanks to:

- The open-source community behind OpenCV, NumPy, and SciPy
- AIM Global for the DotCode specification
- Contributors who helped test and improve the decoder

---

**Questions or support:** open a [GitHub issue](https://github.com/Anish-karki/dotcode-decoder) or email anishkarki989@gmail.com.
