Skip to content

About

An open-source Python toolkit for reproducible image degradation, computer vision robustness evaluation, dataset processing, and benchmark validation.

Topics

Resources

Code of conduct

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

DegradeLab

Controlled Image Degradation, Computer Vision Robustness Evaluation, and Benchmark Validation

CI Python 3.11+ License: MIT Version 0.1.0

DegradeLab is an open-source Python toolkit and CLI for reproducible image degradation, dataset generation, computer vision classification robustness evaluation, visualization, and benchmark reference validation.

PyPI Status: DegradeLab (v0.1.0 candidate) is currently installed from GitHub (git+https://github.com/TahmidZ68/DegradeLab.git). It is not published on PyPI yet.


Visual Demonstration

Real outputs generated directly by DegradeLab (reproduction script, seed=42):

DegradeLab Visual Overview

Clean synthetic street/calibration scene vs. severity-3 gaussian_noise, gaussian_blur, motion_blur, low_light, fog, rain, and jpeg_compression. Additional severity 1–5 sweeps (09_severity_1_to_5_gaussian_noise.png) and pipeline progression figures (10_pipeline_progression.png) are stored in docs/demo-assets/.


Overview & How It Works

What DegradeLab Does

Original images ──▶ Controlled degradation ──▶ Degraded datasets ──▶ Model evaluation ──▶ Robustness analysis
  • Who it is for: Computer vision researchers, ML engineers, and students testing how classifiers degrade under noise, blur, lighting shifts, atmospheric effects, compression artifacts, and geometric warps.
  • What input you provide: In-memory NumPy arrays (uint8, uint16, float32, float64; grayscale, RGB, or RGBA) or image directories (.png, .jpg, .jpeg, .bmp, .tif, .tiff, .webp) organized cleanly by class folder.
  • What DegradeLab does: Applies deterministic 1..5 severity corruptions or ordered multi-step pipelines using isolated SHA-256 + PCG64 random streams that never mutate source files or global RNG state.
  • What output you get: Reproducible degraded images, complete JSON/YAML provenance records (.meta.json, manifest.json), machine-readable JSON/CSV evaluation reports, and optional PNG/SVG Matplotlib figures.

Problem DegradeLab Solves

Standard training-time data augmentation focuses on stochastic diversity rather than auditable test-time stress testing. Scientific robustness studies require:

  • Standardized 1..5 severity schedules with strict parameter validation.
  • Per-image deterministic seeding derived from stable relative image_ids (invariant to filesystem discovery order and PYTHONHASHSEED).
  • Exact provenance metadata recording sampled parameters, transformation order, seeds, schedule regime, and library version.
  • Strict separation between clean baselines, corrupted evaluation sweeps, and training augmentations.

Key Capabilities

  • 34 Registered Corruptions Across 7 Categories (noise, blur, lighting, weather, digital, spatial, resolution) with validated 1..5 severity schedules and joint RGBA geometric warping.
  • Composable Pipelines (DegradationPipeline): Ordered composition in canonical float32 [0.0, 1.0] precision with fixed or randomized parameter distributions (uniform, randint, choice) and JSON/YAML serialization.
  • 7 Built-in Degradation Profiles: Reusable YAML presets (nighttime_surveillance, low_resolution_cctv, rainy_outdoor, foggy_environment, motion_blurred_camera, low_light_mobile, industrial_inspection) explicitly labeled as controlled synthetic approximations.
  • Non-Destructive Dataset Processing: Recursive discovery, class-label layout preservation, atomic file replacement, overwrite protection, --dry-run, and manifest.json generation.
  • Classification Robustness Evaluation: Clean vs. degraded evaluation (ClassificationEvaluator, EvaluationRunner), pure-NumPy metrics (accuracy, absolute/relative drop, confusion matrix, macro/weighted F1), JSON/CSV exports, and optional CPU/CUDA PyTorch/Torchvision integration.
  • Benchmark Audit & Validation (degradelab.benchmarks): Formal compatibility matrix across all 34 native corruptions vs. Hendrycks & Dietterich (ICLR 2019), separate ImageNet-C/CIFAR-C registries, and strict separation between official ImageNet-C AlexNet mCE and custom baseline-normalized ratios.
  • Optional Visualization (degradelab[viz]): Headless Matplotlib (FigureCanvasAgg) comparison grids, severity sweeps, pipeline step progressions, and multi-model evaluation charts (PNG/SVG).

Supported Corruption Categories (34 Native Corruptions)

Category Count Registered Corruptions (degradelab.registry)
noise 6 gaussian_noise, poisson_noise, salt_and_pepper_noise, impulse_noise, speckle_noise, sensor_noise
blur 5 gaussian_blur, motion_blur, defocus_blur, zoom_blur, median_blur
lighting 8 low_light, brightness, contrast, gamma_distortion, overexposure, uneven_illumination, shadow_simulation, lens_flare
weather 5 fog, haze, rain, snow, frost
digital 5 jpeg_compression, pixelation, color_quantization, posterization, bit_depth_reduction
spatial 4 affine_transform, perspective_transform, elastic_transform, random_occlusion
resolution 1 resolution_downscale

See docs/corruptions.md for mathematical definitions, severity 1..5 schedules, and physical limitations.


Installation

Supported Python versions: Python 3.11+ (verified on Ubuntu 3.11/3.12 and Windows 3.12 in CI).

Core vs. Optional: The base package runs on CPU with pure-NumPy/OpenCV/Pillow/SciPy and requires neither PyTorch nor Matplotlib.

Note: DegradeLab is not yet published on PyPI. Do not run pip install degradelab until an official PyPI release is announced. Install directly from GitHub or a local clone as shown below.

Basic Installation (From GitHub)

python -m pip install git+https://github.com/TahmidZ68/DegradeLab.git

To install from GitHub with optional features (for example Matplotlib visualizations or all runtime extras):

python -m pip install "degradelab[viz] @ git+https://github.com/TahmidZ68/DegradeLab.git"
python -m pip install "degradelab[all] @ git+https://github.com/TahmidZ68/DegradeLab.git"

Contributor / Source Installation

git clone https://github.com/TahmidZ68/DegradeLab.git
cd DegradeLab
python -m venv .venv

Activate the virtual environment:

  • Windows PowerShell:
    .venv\Scripts\Activate.ps1
  • Linux / macOS:
    source .venv/bin/activate

Upgrade pip and install editable dependencies:

python -m pip install --upgrade pip
python -m pip install -e ".[all]"

For development (testing, linting, type checking, visualization, and packaging tools):

python -m pip install -e ".[dev,viz]"

Optional Dependency Groups

Extra Packages Included Purpose
[torch] torch>=2.1, torchvision>=0.16 PyTorchClassificationAdapter, create_torch_dataset, load_torchvision_classifier
[detection] torch>=2.1, torchvision>=0.16, pycocotools>=2.0.7 Milestone 01 Faster R-CNN COCO object detection baseline (degradelab.detection)
[viz] matplotlib>=3.8 Headless PNG/SVG comparison grids and evaluation plots (degradelab.visualization)
[eval] pandas>=2.1 Optional tabular inspection of CSV outputs
[integrations] albumentations>=1.4, kornia>=0.7 Optional external augmentation ecosystem extras
[dev] pytest, pytest-cov, ruff, mypy, types-PyYAML, pre-commit, build Test suite, coverage, linting, strict type checking, and wheel builds
[all] torch, torchvision, matplotlib, pandas All optional runtime integrations together

Verify Your Installation

degradelab info
python -c "import degradelab; print(degradelab.__version__, len(degradelab.registry), len(degradelab.list_profiles()))"

Expected check output includes 0.1.0 34 7 alongside installed optional dependency status.

Troubleshooting Common Installation Issues

  • Python version incompatibility (Requires-Python >=3.11): Check python --version. On systems with multiple Python versions, run py -3.11 -m venv .venv (Windows) or python3.12 -m venv .venv (Linux/macOS).
  • Virtual environment not active (degradelab: command not found): Ensure you ran the activation command above, or invoke python -m degradelab.cli.app info / .venv\Scripts\degradelab.exe info directly.
  • Git not installed (Cannot find command 'git' during pip install git+...): Install Git and restart your terminal so git is on PATH.
  • Windows PowerShell blocks .venv\Scripts\Activate.ps1 (running scripts is disabled): Run Set-ExecutionPolicy -Scope CurrentUser RemoteSigned once in PowerShell, or run .venv\Scripts\python.exe without activating.
  • Missing optional dependencies (OptionalDependencyError): Core installs intentionally omit PyTorch and Matplotlib. Install "degradelab[viz] @ ..." or "degradelab[torch] @ ..." as needed.
  • OpenCV GUI/headless conflicts (cv2 import error or ImportError: libGL.so.1): DegradeLab uses opencv-python-headless. If another package installed opencv-python in the same environment, uninstall both and reinstall opencv-python-headless.
  • Dependency build or PyTorch wheel errors: Upgrade pip (python -m pip install --upgrade pip) and, for CPU-only PyTorch on Linux/Windows without large CUDA downloads, install CPU PyTorch via python -m pip install torch --index-url https://download.pytorch.org/whl/cpu.

Five-Minute Quickstart

For the full annotated walkthrough (loading or generating an image, noise/blur, severities 1..5, pipelines, metadata inspection, and Matplotlib comparison grids), see docs/quickstart.md.

import numpy as np
from degradelab import CorruptionStepConfig, DegradationPipeline, registry
from degradelab.utils.io import save_image
from degradelab.utils.metadata import save_metadata

# Synthesize a sample RGB image (or load with load_image("path/to/img.png"))
image = np.full((128, 128, 3), 180, dtype=np.uint8)
image[32:96, 32:96] = [40, 200, 120]

# Apply a single corruption with provenance
result = registry.get("gaussian_noise").apply_with_metadata(
    image, severity=3, seed=42, image_id="sample.png"
)
print("Resolved params:", result.metadata.transformations[0].params)

# Compose a reproducible multi-step pipeline
pipeline = DegradationPipeline(
    steps=[
        ("low_light", 2),
        CorruptionStepConfig(corruption="motion_blur", severity=2, params={"angle": 25.0}),
        ("jpeg_compression", 3),
    ],
    seed=42,
    name="quickstart_pipeline",
)
pipe_result = pipeline.apply_with_metadata(image, image_id="sample.png")
save_image(pipe_result.image, "degraded.png", overwrite=True)
save_metadata(pipe_result.metadata, "degraded.meta.json", format="json", overwrite=True)

Python API & Feature Examples

Pipelines & YAML Degradation Profiles

from degradelab import DegradationPipeline, list_profiles, load_profile

print(list_profiles())
profile = load_profile("nighttime_surveillance")
print(profile.disclaimer)  # Labeled as a controlled synthetic approximation

pipeline = DegradationPipeline(profile=profile, seed=42)
degraded = pipeline.apply(image, image_id="cam01_0001.png")

Built-in presets (degradelab/profiles/presets/): foggy_environment, industrial_inspection, low_light_mobile, low_resolution_cctv, motion_blurred_camera, nighttime_surveillance, rainy_outdoor.

Dataset Processing (Non-Destructive)

from degradelab import DegradationPipeline
from degradelab.datasets import process_dataset

pipeline = DegradationPipeline(profile="low_resolution_cctv", seed=42)
manifest = process_dataset(
    input_dir="dataset/clean",
    output_dir="dataset/degraded_cctv",
    pipeline=pipeline,
    save_sidecar_metadata=True,
)
print(manifest.summary)

Existing files are protected by default (overwrite=False), source files are never modified, class directory layouts are preserved, and manifest.json records per-image seeds and resolved parameters.

Classification Robustness Evaluation

from degradelab.evaluation import (
    CallableClassificationAdapter,
    ClassificationExperimentConfig,
    EvaluationRunner,
    PreprocessingConfig,
)

# Use PyTorchClassificationAdapter for torch.nn.Module models on CPU or CUDA
adapter = CallableClassificationAdapter(predict_fn, num_classes=2, name="baseline_model")
config = ClassificationExperimentConfig(
    experiment_name="baseline_robustness",
    dataset_dir="dataset/val",
    output_dir="runs/baseline_eval",
    seed=42,
    batch_size=32,
    preprocessing=PreprocessingConfig(target_size=(64, 64), channel_order="CHW"),
    corruptions=["gaussian_noise", "defocus_blur", "low_light"],
    severities=[1, 3, 5],
    profiles=["nighttime_surveillance"],
)
report = EvaluationRunner(config, adapter).run()
print(report.aggregate_summary)

Visualization (degradelab[viz])

from degradelab.visualization import (
    plot_accuracy_vs_severity,
    plot_evaluation_summary,
    plot_severity_grid,
)

plot_severity_grid(image, "gaussian_noise", seed=42, output_path="severity_grid.png")
plot_accuracy_vs_severity("runs/baseline_eval/evaluation_report.json", output_path="acc.svg")
plot_evaluation_summary("runs/baseline_eval/evaluation_report.json", output_dir="charts")

Command-Line Interface (degradelab)

degradelab --help
degradelab info
degradelab list corruptions --category noise
degradelab list profiles
degradelab profile inspect nighttime_surveillance

# Single image corruption with provenance metadata
degradelab apply -i clean.png -o noisy.png -c gaussian_noise -s 3 --seed 42 --save-metadata

# Apply a YAML profile to a file or directory
degradelab profile apply -n rainy_outdoor -i clean.png -o rainy.png --seed 42

# Dataset processing with non-overwrite protection, dry-run preview, and manifest.json
degradelab dataset process -i ./dataset/clean -o ./dataset/degraded -p nighttime_surveillance --seed 42
degradelab dataset process -i ./dataset/clean -o ./dataset/degraded -c motion_blur -s 3 --dry-run

# Validate custom YAML/JSON profile or pipeline configs
degradelab validate my_profile.yaml

# Run clean vs. degraded classification evaluation
degradelab eval classification -d ./val -o ./reports -m python:model.py:build_model -c low_light -s 1,3,5

Benchmark Compatibility & Validation

DegradeLab strictly separates its native schedules (degradelab.registry) from validated benchmark schedules (degradelab/benchmarks/):

  • degradelab.registry (schedule_type="degradelab", 34 entries): Native DegradeLab schedules designed for general robustness exploration. All 34 entries are audited in get_compatibility_matrix().
  • imagenet_c_registry (schedule_type="benchmark_imagenet_c", 10 entries): Implements 9 of the 15 primary ImageNet-C evaluation corruptions (gaussian_noise, shot_noise, impulse_noise, defocus_blur, zoom_blur, brightness, contrast, pixelate, jpeg_compression) plus 1 extra validation corruption (speckle_noise). Does not implement all 15 primary corruptions (glass_blur, motion_blur, snow, frost, fog, elastic_transform require ImageMagick/wand, external photo assets, or upstream quirks).
  • cifar_c_registry (schedule_type="benchmark_cifar_c", 2 entries): Verified CIFAR-10-C / CIFAR-100-C gaussian_noise and pixelate.
  • Metric Separation:
    • compute_official_imagenet_c_mce() requires all 15 primary ImageNet-C evaluation corruptions and published AlexNet error baselines.
    • compute_mean_baseline_normalized_error() computes custom dataset-baseline ratios (is_official_imagenet_c_mce = False) and is never labeled as official ImageNet-C mCE.
  • Validation Scope: Bit-exact / <= 1e-6 numerical reference validation applies strictly to deterministic benchmark entries (6 ImageNet-C + 1 CIFAR-C pixelate), while stochastic entries use statistical moment validation due to PCG64 vs. global MT19937 RNG isolation. See docs/benchmark_compatibility.md and docs/validation_methodology.md.

Scientific Limitations

  1. Controlled approximations: Corruptions such as rain, fog, snow, frost, shadow_simulation, lens_flare, and sensor_noise (plus all 7 YAML profiles) are 2D/screen-space approximations, not physically validated camera ISP, RAW sensor, or 3D radiative transfer simulations.
  2. Not a real-world guarantee: Strong accuracy on synthetic corruptions does not guarantee robustness on real-world sensor or environmental shifts.
  3. Evaluation and training scope: DegradeLab is not an image-enhancement or restoration model, and it does not automatically train computer vision models. Only classification evaluation is currently implemented (detection, segmentation, and restoration exist only as extensible interface/report placeholders).
  4. Sequential processing: Dataset processing and evaluation execute sequentially by default to prioritize reproducibility and deterministic logging.
  5. Hardware & torchvision caveats: Automated CI runs on CPU without installing external Torchvision pretrained weights; GPU (cuda) inference and Torchvision weights downloads rely on the user's PyTorch/CUDA environment.

Documentation & Examples Index

Guides (docs/)

Runnable Examples (examples/ & experiments/)

Script Topic Optional Extras Needed
01_single_corruption.py Single corruption with provenance metadata None (Core)
02_pipeline_composition.py Deterministic multi-step pipeline with random step parameters None (Core)
03_profile_application.py Loading and applying built-in YAML profiles None (Core)
04_dataset_processing.py Non-destructive dataset processing and manifest.json None (Core)
05_classification_evaluation.py Clean vs. corrupted classification evaluation & JSON report None (Core)
06_visualization.py Generating severity grids and evaluation summary charts [viz] (Matplotlib)
07_benchmark_validation.py Running benchmark audit, deterministic checks, and noise moment checks None (Core)
08_visual_demonstration.py Regenerating all PNG/SVG visual assets under docs/demo-assets/ [viz] (Matplotlib)
robustness_benchmark_experiment.py Synthetic CPU CNN vs. gradient baseline infrastructure demo Optional [torch] (falls back cleanly to CPU NumPy baseline)
detection_baseline.py Milestone 01 Faster R-CNN COCO detection baseline & CPU smoke runner [detection] (torch, torchvision, pycocotools)
exdark_audit.py Milestone 02A ExDark dataset audit, COCO mapping report & split exporter Core + [detection]
exdark_visualize.py Milestone 02A ExDark bounding-box, lighting, class & box visualizations [viz] (Matplotlib)

Project Architecture

degradelab/
├── core/            # BaseCorruption, CorruptionRegistry, DegradationPipeline, SeedManager, schemas
├── corruptions/     # 34 registered corruptions across 7 subpackages
├── profiles/        # YAML DegradationProfile loader/validator + 7 built-in presets
├── datasets/        # Non-destructive recursive dataset processor & manifest schema
├── evaluation/      # Task-agnostic Evaluator, ClassificationEvaluator, EvaluationRunner, JSON/CSV reports
├── detection/       # Milestone 01 Faster R-CNN COCO dataset, transforms, training, and evaluation
├── metrics/         # Explicit NumPy classification, custom-baseline, and official ImageNet-C mCE metrics
├── benchmarks/      # Compatibility audit matrix, validation suites, ImageNet-C & CIFAR-C registries
├── integrations/    # Optional lazy-imported PyTorch & Torchvision adapters
├── visualization/   # Optional headless Matplotlib grids & evaluation report charts
├── cli/             # Typer + Rich CLI (`degradelab`)
└── utils/           # Atomic image/text I/O, JSON/YAML metadata, structured logging

Contributing, Citation & License

@software{degradelab_2026,
  title   = {DegradeLab: Controlled Image Degradation and Computer Vision Robustness Toolkit},
  author  = {Tahmid Zoayed},
  version = {0.1.0},
  year    = {2026},
  url     = {https://github.com/TahmidZ68/DegradeLab},
  license = {MIT}
}

Roadmap

  • Complete remaining primary ImageNet-C reference corruptions where license- and dependency-compatible.
  • Optional deterministic worker pools for large-scale dataset generation.
  • Object detection, semantic segmentation, and image restoration evaluators matching the extensible EvaluationReport contract.
  • PyPI package release after public v0.1.0 verification.

About

An open-source Python toolkit for reproducible image degradation, computer vision robustness evaluation, dataset processing, and benchmark validation.

Topics

Resources

Code of conduct

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages