Metadata-Version: 2.4
Name: defect-synthesis
Version: 0.1.0
Summary: Procedural anomaly and surface defect synthesis engine for industrial visual inspection, quality control, and anomaly detection.
Author-email: Anirudh <author@defectsynthesis.org>
License: Apache-2.0
Project-URL: Homepage, https://github.com/anirudhk/defect-synthesis
Project-URL: Repository, https://github.com/anirudhk/defect-synthesis
Keywords: anomaly-detection,surface-defects,synthetic-data,mvtec-ad,quality-control,crack-detection,industrial-inspection,computer-vision
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Scientific/Engineering :: Image Processing
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.22.0
Requires-Dist: opencv-python>=4.6.0
Requires-Dist: Pillow>=9.0.0
Requires-Dist: scipy>=1.8.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
Dynamic: license-file

# defect-synthesis

[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
[![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-green.svg)](https://opensource.org/licenses/Apache-2.0)
[![Test Suite](https://img.shields.io/badge/tests-passing-brightgreen.svg)]()

> **Procedural anomaly and surface defect synthesis engine for industrial visual inspection, quality control, and zero-shot anomaly detection.**

---

## 🌟 Why defect-synthesis?

Real-world computer vision models for defect detection (e.g., MVTec AD benchmarks, PatchCore, PaDiM, FastFlow, YOLO-seg) suffer from severe data scarcity: defective samples in manufacturing are rare, unpredictable, and expensive to curate and annotate at pixel precision.

`defect-synthesis` generates photorealistic, physics-grounded procedural surface anomalies directly on real seed images with **exact, pixel-perfect ground-truth anomaly masks**:

1. **6 Diverse Defect Modalities**:
   - **Directional Scratches & Abrasions**: Dark core trenches with adjacent specular highlight ridges.
   - **Branched Fractures & Structural Cracks**: Recursive random-walk branching with tapering kerf widths.
   - **Fluid Stains & Moisture Discoloration**: Capillary diffusion gradients for oils, rust, water droplets, and chemical blemishes.
   - **Corrosion Pitting & Pinhole Voids**: Cellular indentations with shadowed cavities and reflective rims.
   - **Thermal Burns & Laser Marks**: Scorched dark cores with radial heat discoloration rings.
   - **Elastic Surface Warping**: Localized displacement-field distortions simulating dents, ripples, and fabric wrinkles.
2. **ROI (Region of Interest) Masking**: Confines defects strictly to target object parts (e.g. only on polished metal surfaces, avoiding screws or backgrounds).
3. **MVTec AD Benchmark Exporter**: Automatically formats datasets according to the official standard used by anomaly detection researchers:
   ```
   dataset/
   ├── train/good/
   ├── test/good/
   ├── test/<defect_name>/
   └── ground_truth/<defect_name>/<sample_id>_mask.png
   ```
4. **YOLO-seg Exporter**: Exports images and normalized polygon segmentation labels for direct supervised training with YOLOv8/v11 segmentation.
5. **Quality Inspection Visualizer**: Renders color anomaly heatmaps (JET/TURBO) and side-by-side 4-panel inspection cards.

---

## 📦 Installation

```bash
pip install defect-synthesis
```

Or install with development dependencies:

```bash
pip install defect-synthesis[dev]
```

---

## 🚀 Quickstart

### 1. Generating Procedural Defects on a Seed Image

```python
import cv2
from defect_synthesis import (
    ScratchGenerator,
    CrackGenerator,
    StainGenerator,
    render_inspection_card,
)

# Load clean seed image of an industrial part or surface
image = cv2.imread("metal_part.jpg")

# 1. Generate scratches with specular highlights
scratch_gen = ScratchGenerator(stroke_count_range=(2, 4), length_range=(40, 120))
scratch_res = scratch_gen.apply(image)

print(f"Defect area: {scratch_res.defect_area} px ({scratch_res.defect_ratio:.2%})")
print(f"Bounding boxes: {scratch_res.get_bounding_boxes()}")

# 2. Render side-by-side inspection card
card = render_inspection_card(clean_image=image, defect_result=scratch_res)
cv2.imwrite("scratch_inspection_card.jpg", card)
```

---

### 2. Composable Multi-Defect Pipeline with ROI

```python
from defect_synthesis import DefectPipeline, CrackGenerator, PittingGenerator

pipeline = DefectPipeline()
pipeline.add(CrackGenerator(branch_probability=0.4), probability=0.7)
pipeline.add(PittingGenerator(cluster_size_range=(5, 15)), probability=0.5)

# Optional binary mask restricting defects to specific areas
roi_mask = cv2.imread("metal_surface_mask.png", cv2.IMREAD_GRAYSCALE)

result = pipeline.apply(image, roi_mask=roi_mask, allow_multiple=True)
print(f"Applied defects: {result.metadata['applied_defects']}")
```

---

### 3. Exporting to MVTec AD Format

```python
from defect_synthesis import MvTecExporter

exporter = MvTecExporter(output_dir="./mvtec_metal_parts")
exporter.export(
    clean_train_images=train_good_list,
    clean_test_images=test_good_list,
    defective_results=[res1, res2, res3],
)
```

---

## 🏛️ Architecture Overview

```
src/defect_synthesis/
├── core/                  # DefectType enum, DefectResult container with bounding box extraction
├── generators/            # ScratchGenerator, CrackGenerator, StainGenerator, Pitting, Burn, Warping
├── pipeline/              # DefectPipeline chaining multiple generators with ROI masking
├── exporters/             # MvTecExporter (MVTec AD layout), YoloAnomalyExporter
└── visualizer/            # render_anomaly_overlay (heatmaps), render_inspection_card
```

---

## 🧪 Running Tests

```bash
pytest tests/ -v
```

---

## 📄 License

Licensed under the [Apache License, Version 2.0](LICENSE).
