Skip to main content

defect-synthesis

Python 3.10+ License: Apache 2.0 Test Suite

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

pip install defect-synthesis

Or install with development dependencies:

pip install defect-synthesis[dev]

🚀 Quickstart

1. Generating Procedural Defects on a Seed Image

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

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

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

pytest tests/ -v

📄 License

Licensed under the Apache License, Version 2.0.

Metadata

Release files for defect-synthesis 0.1.0

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

Source distribution (sdist)

Source distribution for defect-synthesis 0.1.0
File Size Uploaded Provenance
defect_synthesis-0.1.0.tar.gz 19.9 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for defect-synthesis 0.1.0
File Interpreter ABI Platform
defect_synthesis-0.1.0-py3-none-any.whl Python 3 none any Details

Total release size: 42.6 kB

Release files / defect_synthesis-0.1.0.tar.gz

Download URL defect_synthesis-0.1.0.tar.gz
Size 19.9 kB
Tags Source
SHA-256 checksum
How to use checksums
130160b265ebafcaf57b693a1b7a28a59d423098df90ca05e4773d8281519e3f
BLAKE2b-256 checksum
How to use checksums
9ab30d2e3053609045fba556bd1028ca4109e9229d0a1885bd549aef17955232
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.10

Release files / defect_synthesis-0.1.0-py3-none-any.whl

Download URL defect_synthesis-0.1.0-py3-none-any.whl
Size 22.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
aa66b1d0f2a1cb458261ee1c73881cc90bcae886fa67088367a01d78ab5d4245
BLAKE2b-256 checksum
How to use checksums
b3e87664e0695c87cf4f0cef39dd1d490ed5d65730af057c8f0a864efa7770fc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.10

Security for defect-synthesis 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

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