imgad 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. imgad-0.1.0/LICENSE +202 -0
  2. imgad-0.1.0/PKG-INFO +434 -0
  3. imgad-0.1.0/README.md +376 -0
  4. imgad-0.1.0/pyproject.toml +68 -0
  5. imgad-0.1.0/setup.cfg +4 -0
  6. imgad-0.1.0/src/imgad/__init__.py +70 -0
  7. imgad-0.1.0/src/imgad/anomalib_backend.py +489 -0
  8. imgad-0.1.0/src/imgad/cli.py +384 -0
  9. imgad-0.1.0/src/imgad/data.py +133 -0
  10. imgad-0.1.0/src/imgad/detectors/__init__.py +36 -0
  11. imgad-0.1.0/src/imgad/detectors/base.py +142 -0
  12. imgad-0.1.0/src/imgad/detectors/classical.py +350 -0
  13. imgad-0.1.0/src/imgad/evaluation.py +299 -0
  14. imgad-0.1.0/src/imgad/features/__init__.py +12 -0
  15. imgad-0.1.0/src/imgad/features/base.py +121 -0
  16. imgad-0.1.0/src/imgad/features/huggingface.py +199 -0
  17. imgad-0.1.0/src/imgad/features/open_clip.py +64 -0
  18. imgad-0.1.0/src/imgad/inference.py +225 -0
  19. imgad-0.1.0/src/imgad/maps.py +60 -0
  20. imgad-0.1.0/src/imgad/pipeline.py +250 -0
  21. imgad-0.1.0/src/imgad/preprocessing.py +49 -0
  22. imgad-0.1.0/src/imgad/report.py +1063 -0
  23. imgad-0.1.0/src/imgad/stats.py +391 -0
  24. imgad-0.1.0/src/imgad/utils.py +59 -0
  25. imgad-0.1.0/src/imgad.egg-info/PKG-INFO +434 -0
  26. imgad-0.1.0/src/imgad.egg-info/SOURCES.txt +34 -0
  27. imgad-0.1.0/src/imgad.egg-info/dependency_links.txt +1 -0
  28. imgad-0.1.0/src/imgad.egg-info/entry_points.txt +2 -0
  29. imgad-0.1.0/src/imgad.egg-info/requires.txt +38 -0
  30. imgad-0.1.0/src/imgad.egg-info/top_level.txt +1 -0
  31. imgad-0.1.0/tests/test_anomalib.py +136 -0
  32. imgad-0.1.0/tests/test_detectors.py +63 -0
  33. imgad-0.1.0/tests/test_inference.py +94 -0
  34. imgad-0.1.0/tests/test_pipeline.py +107 -0
  35. imgad-0.1.0/tests/test_report.py +66 -0
  36. imgad-0.1.0/tests/test_stats.py +131 -0
imgad-0.1.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
imgad-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,434 @@
1
+ Metadata-Version: 2.4
2
+ Name: imgad
3
+ Version: 0.1.0
4
+ Summary: Image anomaly detection with foundation-model features (CLIP, SigLIP, DINOv2) + classical detectors, Anomalib models, and statistical benchmarking
5
+ Author: Jónathan Heras
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/joheras/imgad
8
+ Project-URL: Repository, https://github.com/joheras/imgad
9
+ Project-URL: Issues, https://github.com/joheras/imgad/issues
10
+ Keywords: anomaly-detection,one-class,computer-vision,foundation-models,clip,dinov2,anomalib,patchcore,mvtec,benchmark
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
+ Classifier: Topic :: Scientific/Engineering :: Image Recognition
23
+ Requires-Python: >=3.10
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: numpy>=1.23
27
+ Requires-Dist: scipy>=1.9
28
+ Requires-Dist: scikit-learn>=1.2
29
+ Requires-Dist: torch>=2.0
30
+ Requires-Dist: transformers>=4.40
31
+ Requires-Dist: pillow>=9.0
32
+ Requires-Dist: joblib>=1.2
33
+ Requires-Dist: pyyaml>=6.0
34
+ Requires-Dist: tqdm>=4.60
35
+ Provides-Extra: open-clip
36
+ Requires-Dist: open_clip_torch>=2.20; extra == "open-clip"
37
+ Provides-Extra: pyod
38
+ Requires-Dist: pyod>=1.1; extra == "pyod"
39
+ Provides-Extra: pandas
40
+ Requires-Dist: pandas>=1.5; extra == "pandas"
41
+ Provides-Extra: anomalib
42
+ Requires-Dist: anomalib>=2.0; extra == "anomalib"
43
+ Provides-Extra: report
44
+ Requires-Dist: matplotlib>=3.5; extra == "report"
45
+ Provides-Extra: dev
46
+ Requires-Dist: pytest>=7; extra == "dev"
47
+ Requires-Dist: matplotlib>=3.5; extra == "dev"
48
+ Requires-Dist: build; extra == "dev"
49
+ Requires-Dist: twine; extra == "dev"
50
+ Provides-Extra: all
51
+ Requires-Dist: open_clip_torch>=2.20; extra == "all"
52
+ Requires-Dist: pyod>=1.1; extra == "all"
53
+ Requires-Dist: pandas>=1.5; extra == "all"
54
+ Requires-Dist: anomalib>=2.0; extra == "all"
55
+ Requires-Dist: matplotlib>=3.5; extra == "all"
56
+ Requires-Dist: pytest>=7; extra == "all"
57
+ Dynamic: license-file
58
+
59
+ # imgad — Image anomaly detection with foundation models, classical detectors and Anomalib
60
+
61
+ [![CI](https://github.com/joheras/imgad/actions/workflows/ci.yml/badge.svg)](https://github.com/joheras/imgad/actions/workflows/ci.yml)
62
+ [![PyPI](https://img.shields.io/pypi/v/imgad.svg)](https://pypi.org/project/imgad/)
63
+ [![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](https://github.com/joheras/imgad/blob/main/LICENSE)
64
+
65
+ A modular framework for image-level anomaly detection in the **one-class** setting (training uses
66
+ normal images only):
67
+
68
+ ```
69
+ images ──► FeatureExtractor ──► preprocessing ──► classical detector ──► anomaly score
70
+ (CLIP, SigLIP, DINOv2… (l2, PCA, (kNN, Mahalanobis, (+ calibrated threshold)
71
+ any HF model) standard…) LOF, OCSVM, IF…)
72
+ ```
73
+
74
+ It also wraps end-to-end [Anomalib](https://github.com/open-edge-platform/anomalib) models (PatchCore,
75
+ PaDiM, EfficientAD…) with pixel-level anomaly maps, and includes a benchmarking module with repeated
76
+ runs, confidence intervals, statistical tests and automatic markdown reports.
77
+
78
+ ## Installation
79
+
80
+ ```bash
81
+ pip install imgad # core
82
+ pip install "imgad[anomalib]" # + Anomalib models (PatchCore, PaDiM, EfficientAD…)
83
+ pip install "imgad[report]" # + figures in benchmark reports (matplotlib)
84
+ pip install "imgad[all]" # + open_clip, pyod, pandas, anomalib, matplotlib, pytest
85
+ ```
86
+
87
+ From source: `git clone https://github.com/joheras/imgad && pip install -e "imgad[dev]"`.
88
+ Python ≥ 3.10.
89
+
90
+ ## Quick start
91
+
92
+ ```python
93
+ from imgad import AnomalyDetectionPipeline, HFFeatureExtractor, build_detector, data
94
+ from imgad.evaluation import evaluate_scores
95
+
96
+ ds = data.mvtec_ad("/path/to/mvtec_anomaly_detection", "bottle")
97
+
98
+ pipe = AnomalyDetectionPipeline(
99
+ extractor=HFFeatureExtractor("openai/clip-vit-base-patch16"),
100
+ detector=build_detector("knn", k=1),
101
+ preprocessing=["l2"],
102
+ cache_dir=".feature_cache", # caches features per image
103
+ )
104
+ pipe.fit(ds.train_paths) # normal images only
105
+ scores = pipe.score(ds.test_paths) # higher = more anomalous
106
+ preds = pipe.predict(ds.test_paths) # 0/1 with the calibrated threshold
107
+ print(evaluate_scores(ds.test_labels, scores, preds))
108
+
109
+ pipe.save("bottle.joblib") # saves detector + config (not the model weights)
110
+ pipe = AnomalyDetectionPipeline.load("bottle.joblib")
111
+ ```
112
+
113
+ ## Inference with a trained model
114
+
115
+ The `.joblib` file stores the fitted detector, the preprocessing, the threshold, the extractor
116
+ configuration and metadata (number of training images, date, threshold origin). Hugging Face weights
117
+ are not stored: they are reloaded from the Hub (or the local HF cache) on `load`.
118
+
119
+ ```python
120
+ from imgad import AnomalyPredictor
121
+
122
+ predictor = AnomalyPredictor.load("bottle.joblib") # device auto (cuda/mps/cpu); device="cpu" to force it
123
+ r = predictor.predict_one("new.png") # path, PIL.Image or numpy array
124
+ r.is_anomaly, r.score, r.normal_percentile
125
+
126
+ results = predictor.predict("folder/") # folder, list of paths/images, or a mix
127
+ predictor.save_results(results, "preds.csv") # .csv or .json
128
+ for r in predictor.predict_iter("huge_folder/", chunk_size=256): ... # constant memory
129
+ ```
130
+
131
+ Each `Prediction` contains:
132
+
133
+ | Field | Meaning |
134
+ |---|---|
135
+ | `score` | raw score (detector-dependent scale; higher = more anomalous) |
136
+ | `is_anomaly` | `score > threshold` |
137
+ | `threshold` | threshold used |
138
+ | `normal_percentile` | fraction of normal training images with a lower score (0–1). Comparable across detectors: ~0.5 = typical normal image, 1.0 = rarer than any normal image seen |
139
+
140
+ **Tune the threshold** on a labelled validation set (no retraining):
141
+
142
+ ```python
143
+ pipe = AnomalyDetectionPipeline.load("bottle.joblib")
144
+ pipe.calibrate_threshold(val_paths, val_labels, method="f1") # f1 | youden | fpr | tpr
145
+ pipe.save("bottle_cal.joblib")
146
+ # Normal images only: method="fpr", target_fpr=0.01 -> ≤1% false alarms
147
+ ```
148
+
149
+ Or on the fly: `AnomalyPredictor.load("bottle.joblib", threshold=0.02)`.
150
+
151
+ Shortcuts: the extractor can be an HF id (`"facebook/dinov2-base"`) and the detector a name
152
+ (`"mahalanobis"`) or a dict (`{"name": "knn", "k": 5}`).
153
+
154
+ ## Feature extractors
155
+
156
+ `HFFeatureExtractor(model_name, pooling="auto", layer=None, normalize=True, ...)` works with any
157
+ vision model on the Hub that loads with `AutoModel`:
158
+
159
+ | Family | Examples | Default pooling |
160
+ |---|---|---|
161
+ | CLIP-style dual encoders | `openai/clip-*`, `google/siglip-*`, `google/siglip2-*`, `facebook/metaclip-*`, `kakaobrain/align-base`, `laion/CLIP-*` (HF format) | `projection` → `get_image_features` |
162
+ | Vision backbones | `facebook/dinov2-*`, `google/vit-*`, `microsoft/beit-*`, `facebook/convnext-*`, `microsoft/resnet-*` | `pooler` |
163
+
164
+ `pooling` options: `auto`, `projection`, `pooler`, `cls`, `mean` (mean of patch tokens), `cls+mean`.
165
+ `layer` selects intermediate layers (`layer=-4`, or `layer=[6, 9, 12]` to concatenate several), which
166
+ often capture local defects better than the more semantic last layer.
167
+
168
+ For **open_clip** checkpoints (`hf-hub:laion/...`, EVA-CLIP, DataComp…):
169
+ `OpenCLIPFeatureExtractor("hf-hub:laion/CLIP-ViT-B-32-laion2B-s34B-b79K")`.
170
+
171
+ ## Detectors
172
+
173
+ All detectors share the same API (`fit`, `score`, `predict`) and the convention **higher score = more
174
+ anomalous**.
175
+
176
+ | Name | Method | Notes |
177
+ |---|---|---|
178
+ | `knn` | Distance to the k nearest normal samples | Very strong baseline with CLIP/DINO; `metric="cosine"` |
179
+ | `mahalanobis` / `gaussian` | Mahalanobis distance (Ledoit-Wolf, OAS, MCD) | Very good with foundation-model features |
180
+ | `centroid` | Distance to the mean embedding | Minimal cost |
181
+ | `kmeans` | Distance to the nearest centroid | Multimodal normality |
182
+ | `lof` | Local Outlier Factor (novelty mode) | |
183
+ | `gmm` | Negative log-likelihood under a Gaussian mixture | |
184
+ | `kde` | Negative KDE log-density | Better after `pca:<n>` to few dimensions |
185
+ | `ocsvm` | One-Class SVM | |
186
+ | `iforest` | Isolation Forest | |
187
+ | `pca` | PCA reconstruction error | |
188
+ | `ensemble` | Mean of normalised detectors (z-score or rank) | |
189
+ | `sklearn` | Wraps any sklearn estimator | `SklearnDetector(estimator=EllipticEnvelope())` |
190
+ | `pyod` | Any PyOD model | `{"name": "pyod", "model": "ECOD"}` |
191
+
192
+ **Threshold**: after `fit`, `threshold_` is set to the `threshold_quantile` (0.95 by default) of
193
+ *out-of-sample* scores of the normal data: leave-one-out for kNN/LOF and 5-fold cross-validation for
194
+ the rest. This avoids the optimistic threshold of detectors that overfit the training set (KDE, OCSVM,
195
+ PCA…). It can be disabled with `det.calibration = "train"`.
196
+
197
+ ## Anomalib models (with anomaly maps)
198
+
199
+ `AnomalibPipeline` wraps any **one-class** [Anomalib](https://github.com/open-edge-platform/anomalib)
200
+ model (`patchcore`, `padim`, `efficient_ad`, `fastflow`, `stfpm`, `reverse_distillation`, `cflow`,
201
+ `draem`…; `imgad list` shows them) with the same API as the feature pipelines, and adds **pixel-level
202
+ anomaly maps**:
203
+
204
+ ```python
205
+ from imgad import AnomalibPipeline, evaluate_maps
206
+
207
+ pc = AnomalibPipeline("patchcore", backbone="wide_resnet50_2", layers=["layer2", "layer3"], image_size=256)
208
+ pc.fit(ds.train_paths) # normal images only
209
+ scores, maps = pc.score_and_maps(ds.test_paths) # maps: list of arrays (model resolution)
210
+ evaluate_maps(ds.test_masks, maps) # pixel_auroc, pixel_aupr, pixel_f1_max, aupro
211
+ pc.predict_masks(maps) # binary masks (map > pixel_threshold_)
212
+ pc.save("bottle_pc.joblib") # loaded by AnomalyPredictor.load / imgad predict as usual
213
+ ```
214
+
215
+ - Anomalib provides the models and the training loop; its post-processing (normalisation and threshold
216
+ learnt on a labelled validation set) is disabled. Scores and maps are the **raw** model outputs
217
+ (higher = more anomalous).
218
+ - **Threshold**: as for the detectors, the `threshold_quantile` (0.95) of the scores of *unseen* normal
219
+ images: `calibration_split=0.2` holds out that 20% of the training images (not used for training).
220
+ `calibration_split=0` uses training scores (optimistic, especially for PatchCore). The pixel threshold
221
+ (`pixel_threshold_`) is the same quantile of the maximum of each held-out normal map; with validation
222
+ masks it can be tuned with `calibrate_pixel_threshold(images, masks)` (pixel F1).
223
+ `calibrate_threshold` works as in the other pipelines.
224
+ - Images are resized to `image_size` **without cropping**, so the maps cover the whole image.
225
+ `score_and_maps(..., size="original")` returns them at each image's own size.
226
+ - The `.joblib` stores the configuration **and the weights** (e.g. the PatchCore memory bank): nothing
227
+ needs to be downloaded to load it.
228
+ - Model kwargs are those of the Anomalib constructor (`backbone`, `layers`, `coreset_sampling_ratio`,
229
+ `pre_trained`…). For models trained over several epochs: `max_epochs` or
230
+ `trainer_kwargs={"max_steps": ...}`. EfficientAD trains with batch size 1 and downloads imagenette.
231
+ - One-class models only; zero/few-shot models (WinCLIP, AnomalyDINO…) are not supported.
232
+
233
+ Inference with maps:
234
+
235
+ ```python
236
+ predictor = AnomalyPredictor.load("bottle_pc.joblib")
237
+ res = predictor.predict("folder/", return_maps=True) # r.anomaly_map (original size), r.anomalous_area
238
+ predictor.save_maps(res, "maps/") # <folder>_<name>_heatmap.png + _mask.png
239
+ predictor.save_results(res, "preds.csv") # includes the heatmap and mask paths
240
+ ```
241
+
242
+ Heatmaps use a fixed scale per model (blue = typical normal, middle of the scale = pixel threshold,
243
+ red = far above it), so normal images look blue instead of being rescaled.
244
+
245
+ ## Preprocessing
246
+
247
+ List of steps applied before the detector (fitted on the normal data):
248
+ `"l2"`, `"standard"`, `"center"`, `"pca:0.95"` (explained variance) or `"pca:64"` (components),
249
+ `"pca_whiten:<n>"`, or any sklearn transformer.
250
+
251
+ ## Data
252
+
253
+ ```python
254
+ data.mvtec_ad(root, "screw") # MVTec AD / MVTec layout (converted VisA, etc.)
255
+ data.from_folders(train_normal, test_normal, [test_anom_1, test_anom_2])
256
+ data.one_vs_rest(root, normal_class="cat") # semantic AD from a classification dataset
257
+ ```
258
+
259
+ Each returns an `AnomalyDataset` with `train_paths`, `test_paths`, `test_labels`, `test_types` and, for
260
+ MVTec, `test_masks` (path of the ground-truth mask in `ground_truth/<type>/<name>_mask.png`, or `None`
261
+ for normal images).
262
+
263
+ ## Evaluation and benchmarks
264
+
265
+ `evaluate_scores` returns AUROC, AUPR, F1-max and FPR@95%TPR (and F1/TPR/FPR at the threshold if
266
+ predictions are given). `per_type_auroc` breaks the AUROC down by defect type.
267
+
268
+ `evaluate_maps(masks, maps)` gives the localisation metrics: pixel-AUROC, pixel-AUPR, pixel-F1-max and
269
+ AUPRO (FPR ≤ 0.3, the standard MVTec AD metric). Masks are resized to each map's resolution.
270
+
271
+ `benchmark(extractors, detectors, datasets, preprocessings, anomalib_models=[...])` evaluates the full
272
+ grid, extracting features once per (extractor, dataset), plus each Anomalib model per dataset (with
273
+ pixel metrics when masks are available). In YAML, use the `anomalib:` key (see
274
+ `configs/mvtec_benchmark.yaml`).
275
+
276
+ ## Benchmark reports
277
+
278
+ `imgad benchmark --report DIR` writes a markdown report with figures:
279
+
280
+ ```bash
281
+ imgad benchmark --config configs/mvtec_benchmark.yaml --report report/ --seeds 0 1 2 --bootstrap 1000
282
+ ```
283
+
284
+ ```
285
+ report/
286
+ report.md # the report
287
+ figures/*.png # every figure referenced in the report
288
+ results.csv # one row per dataset × configuration × seed
289
+ config.yaml # configuration used
290
+ ```
291
+
292
+ The report contains:
293
+
294
+ | Section | Content |
295
+ |---|---|
296
+ | Summary | best configuration, runner-up and significance, best extractors/detectors, hardest dataset |
297
+ | Data analysis | images per split, defect types, resolution, masks; example images with ground-truth masks; warnings (small or imbalanced test sets, few training images) |
298
+ | Methods | extractors (with dimension), preprocessing, detectors and Anomalib models with a short description; threshold protocol, metrics, repetitions and statistical tests |
299
+ | Results | ranking table and chart, extractor × detector heatmap, per-dataset results, ROC curves, score histograms with the threshold, per-defect-type AUROC, operating point, pixel-level metrics and example anomaly maps, spread across seeds, Friedman/Nemenyi/Wilcoxon (or DeLong) with a critical-difference diagram, computational cost |
300
+ | Discussion | extractor vs. detector effect, consistency across datasets, significance, hard defect types, Anomalib vs. global features, threshold calibration, localisation |
301
+ | Limitations and reproducibility | caveats derived from the setup, exact command, configuration and environment versions |
302
+
303
+ Figures need matplotlib (`pip install "imgad[report]"`); without it the report contains tables only.
304
+ The summary and discussion are generated from the numbers with simple rules: treat them as a first
305
+ draft to check and complete. To rebuild a report without rerunning the benchmark:
306
+
307
+ ```bash
308
+ imgad benchmark --config cfg.yaml --scores-out scores.joblib
309
+ imgad report --scores scores.joblib --config cfg.yaml --out report/ --title "My benchmark"
310
+ ```
311
+
312
+ From Python: `imgad.report.generate_report(rows, datasets, "report/", config=cfg)` with
313
+ `rows = benchmark(..., keep_scores=True)`.
314
+
315
+ ## Statistical analysis: repetitions, confidence intervals and tests
316
+
317
+ **Repetitions.** `benchmark(..., seeds=[0, 1, 2, 3, 4], train_subsample=0.8)` runs every configuration
318
+ once per seed (column `seed`). The seed sets the detectors' `random_state` (unless the spec fixes it),
319
+ the calibration folds, the Anomalib seed and the **training subset** (`train_subsample`: a fraction if
320
+ float, a number of images if int). Without subsampling, deterministic detectors (kNN, Mahalanobis…)
321
+ give the same result for every seed. Features are extracted once and reused across seeds.
322
+
323
+ **Confidence intervals.** There are two sources of uncertainty, measured separately:
324
+
325
+ | Source | How | Where |
326
+ |---|---|---|
327
+ | Test sample | stratified bootstrap of the test images (`bootstrap=1000`) | `auroc_ci_low/high`, `aupr_ci_low/high` in each row |
328
+ | Training | repetitions with seeds + `train_subsample` | `stats.summarize_seeds(rows)`: mean, standard deviation and t-based CI of the mean |
329
+
330
+ **Statistical tests** (`imgad.stats`):
331
+
332
+ | Question | Test | Function |
333
+ |---|---|---|
334
+ | Does A have a higher AUROC than B **on this dataset**? | DeLong (correlated AUROCs, same images) | `delong_test(y, sa, sb)`, `delong_vs_baseline(rows, base)` |
335
+ | Same for AUPR, F1-max or another metric | paired bootstrap | `paired_bootstrap_test(y, sa, sb, metric="aupr")` |
336
+ | Are there differences between configurations **across datasets**? | Friedman (+ Iman-Davenport correction) | `compare_configs(rows)` |
337
+ | Which pairs differ? | Nemenyi (critical difference of ranks) and Wilcoxon signed-rank + Holm | `compare_configs(rows)["pairs"]`, `plot_cd_diagram` |
338
+
339
+ To compare across datasets, seeds are first averaged within each dataset, and each dataset (e.g. each
340
+ MVTec category) is a block, following Demšar (2006). Wilcoxon-Holm usually has more power with few
341
+ configurations, while Nemenyi is the classical post-hoc test after Friedman and the one drawn in the CD
342
+ diagram. DeLong needs per-image scores (`keep_scores=True`).
343
+
344
+ ```python
345
+ from imgad import benchmark, stats
346
+
347
+ rows = benchmark(extractors, detectors, datasets, seeds=range(5), train_subsample=0.8,
348
+ bootstrap=1000, keep_scores=True, anomalib_models=["patchcore"])
349
+ stats.summarize_seeds(rows) # mean ± std per (dataset, config)
350
+ res = stats.compare_configs(rows, metric="auroc") # also aupr, pixel_auroc, aupro, fpr@95tpr…
351
+ print(stats.report_markdown(res)) # mean ranks, Friedman, CD, pairs with Holm
352
+ stats.plot_cd_diagram(res, "cd.png")
353
+ stats.delong_vs_baseline(rows, baseline=res["configs"][0])
354
+ ```
355
+
356
+ From the CLI:
357
+
358
+ ```bash
359
+ imgad benchmark --config configs/mvtec_benchmark.yaml --seeds 0 1 2 3 4 --train-subsample 0.8 \
360
+ --bootstrap 1000 --out results.csv --scores-out scores.joblib --stats
361
+ imgad stats --results results.csv --metric auroc --cd-plot cd.png --out stats.md
362
+ imgad stats --scores scores.joblib --baseline "openai/clip-vit-base-patch16 | l2 | knn(k=1)" # + DeLong
363
+ ```
364
+
365
+ ## CLI
366
+
367
+ ```bash
368
+ imgad list
369
+ imgad fit --model openai/clip-vit-base-patch16 --detector knn -p k=1 --prep l2 \
370
+ --train data/bottle/train/good --out bottle.joblib
371
+
372
+ # inference: images and/or folders; output to stdout, .csv or .json
373
+ imgad predict --model bottle.joblib new.png data/bottle/test --out preds.csv
374
+ imgad predict --model bottle.joblib folder/ --only-anomalies --threshold 0.02 --device cpu
375
+
376
+ # re-tune the threshold on labelled validation data (f1 | youden | fpr | tpr)
377
+ imgad calibrate --model bottle.joblib --normal val/good --anomalous val/defects --method f1 --out bottle_cal.joblib
378
+ imgad info --model bottle_cal.joblib # configuration, threshold and metadata
379
+
380
+ imgad benchmark --config configs/mvtec_benchmark.yaml --out results.csv --report report/
381
+
382
+ # Anomalib models: -p sets the model kwargs; predict saves heatmaps and masks
383
+ imgad fit --anomalib patchcore -p backbone=wide_resnet50_2 "layers=[layer2,layer3]" \
384
+ --image-size 256 --train data/bottle/train/good --out bottle_pc.joblib
385
+ imgad predict --model bottle_pc.joblib data/bottle/test --maps-dir maps/ --out preds.csv
386
+ ```
387
+
388
+ ## Extending
389
+
390
+ Registering your own detector or extractor makes it available by name in Python, YAML and the CLI (see
391
+ `examples/extending.py`):
392
+
393
+ ```python
394
+ from imgad import BaseDetector, register_detector
395
+
396
+ @register_detector("my_detector")
397
+ class MyDetector(BaseDetector):
398
+ def _fit(self, X): ...
399
+ def _score(self, X): ... # higher = more anomalous
400
+ ```
401
+
402
+ ## Example results
403
+
404
+ [`benchmarks/mvtec_4categories/`](https://github.com/joheras/imgad/tree/main/benchmarks/mvtec_4categories) contains a benchmark of 5 extractors
405
+ × 11 detectors on 4 MVTec AD categories (report, results CSV and configuration).
406
+
407
+ ## Project layout
408
+
409
+ ```
410
+ src/imgad/
411
+ features/ base.py (interface, registry, cache) · huggingface.py · open_clip.py
412
+ detectors/ base.py (interface, registry, calibration) · classical.py
413
+ anomalib_backend.py (AnomalibPipeline) · maps.py (masks, heatmaps)
414
+ preprocessing.py · pipeline.py · inference.py · data.py · evaluation.py · stats.py · report.py · cli.py
415
+ configs/ example benchmark YAML files
416
+ examples/ quickstart.py · inference.py · compare_models.py · extending.py · anomalib_models.py
417
+ benchmarks/ example benchmark results
418
+ tests/ pytest (offline: a tiny CLIP generated locally; untrained ResNet-18 for Anomalib)
419
+ ```
420
+
421
+ ## Possible next steps
422
+
423
+ - **Zero-/few-shot** detection with text prompts (WinCLIP, AnomalyCLIP) using the text encoder.
424
+ - Native PatchCore on patch features of foundation models (CLIP/DINOv2), to compare with Anomalib's (CNN).
425
+ - Test-time augmentation (TTA) and multi-scale aggregation.
426
+ - Few-shot sweep (`train_subsample` = 1, 2, 4, 8… images) reusing the seeds and the tests in `imgad.stats`.
427
+
428
+ ## License
429
+
430
+ Distributed under the [Apache 2.0](https://github.com/joheras/imgad/blob/main/LICENSE) license.
431
+
432
+ ## Acknowledgements
433
+
434
+ This work is partially supported by Agencia de Desarrollo Económico de La Rioja [ADER 2022-I-IDI-00015].