Metadata-Version: 2.4
Name: elpv-crack
Version: 0.1.0
Summary: Crack detection in solar-cell electroluminescence images with classical numerical methods (spline busbar fill, LoG, DBSCAN); non-commercial use
License-Expression: MIT AND CC-BY-NC-SA-4.0
Project-URL: Homepage, https://github.com/giorgimskh/elpv-crack-detection
Project-URL: Report, https://github.com/giorgimskh/elpv-crack-detection/blob/main/report/report.pdf
Project-URL: Issues, https://github.com/giorgimskh/elpv-crack-detection/issues
Keywords: solar,photovoltaics,electroluminescence,crack detection,image processing
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: Image Processing
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Requires-Dist: numpy>=1.26
Requires-Dist: scipy>=1.11
Requires-Dist: scikit-learn>=1.3
Requires-Dist: scikit-image>=0.22
Requires-Dist: joblib>=1.3
Provides-Extra: plot
Requires-Dist: matplotlib>=3.7; extra == "plot"
Provides-Extra: research
Requires-Dist: matplotlib>=3.7; extra == "research"
Requires-Dist: elpv-dataset>=1.0; extra == "research"
Dynamic: license-file

# Crack Detection in Solar Cells from Electroluminescence Images

[![tests](https://github.com/giorgimskh/elpv-crack-detection/actions/workflows/tests.yml/badge.svg)](https://github.com/giorgimskh/elpv-crack-detection/actions/workflows/tests.yml)

Finds cracks in solar-cell electroluminescence (EL) images with **classical numerical methods only** (no deep learning) and flags defective cells. Evaluated on the public [ELPV dataset](https://github.com/zae-bayern/elpv-dataset) (2,624 cells).

**Non-commercial use only:** the bundled model is derived from the ELPV dataset (CC BY-NC-SA 4.0); see [License](https://github.com/giorgimskh/elpv-crack-detection#license).

**How it works**
1. **Busbar removal**: the bright horizontal busbars are detected from the row-mean profile and filled by **spline interpolation** (smoothing, cubic or linear).
2. **Crack-line detection**: a **Laplacian of Gaussian** with a 5-point finite-difference stencil, then a threshold.
3. **Grouping**: candidate pixels are clustered into individual cracks with **DBSCAN**, and line-like clusters are kept with a covariance-eigenvalue elongation filter.
4. **Scoring**: crack length and dark-area features are turned into a percentile score against healthy training cells.

**Result on the held-out test half (1,165 cells):** AUC = 0.797 (95% CI 0.77–0.82), accuracy 0.782.

The full write-up (9-page report and slides) is in [`report/report.pdf`](https://github.com/giorgimskh/elpv-crack-detection/blob/main/report/report.pdf) and [`presentation/presentation.pdf`](https://github.com/giorgimskh/elpv-crack-detection/blob/main/presentation/presentation.pdf). Sections 2–4 describe this percentile rule; Section 5 covers the later extensions (logistic rule, calibration, module mode, cells from other sources).

**Improved rule (the package default, added after the report).** Six measurements of the same pipeline (dim area, dead area, fine and coarse line response, crack area, candidate pixels) are combined by logistic regression. Everything was chosen and fitted on the TRAIN half only (`code/select_features.py`, `code/build_model.py`); on the same held-out test cells:

| rule | AUC (95% CI) | accuracy | defects found | healthy passed | mono AUC | poly AUC |
|---|---|---|---|---|---|---|
| percentile (report) | 0.797 (0.77–0.82) | 0.782 | 58.4 % | 89.0 % | 0.836 | 0.759 |
| **logistic (default)** | **0.854** (0.83–0.88) | **0.791** | **63.5 %** | 87.5 % | **0.875** | **0.836** |

The AUC gain is +0.057 (paired bootstrap 95% CI +0.034 to +0.078, printed by `build_model.py --evaluate`). `--method percentile` gives the report's rule exactly.

## Quick start: check your own cell images

```bash
pip install .                    # from the project root; add [plot] for --figure: pip install ".[plot]"

# one image: every step is explained, then OK / DEFECTIVE
crack-detect cell.png --type mono
crack-detect cell.png --type poly --figure stages.png   # also save a picture of all stages
crack-detect cell.png --type mono --json                # machine-readable result
crack-detect cell.png --type mono --method percentile   # the simpler rule of the report

# many images: a folder (add --recursive for subfolders) or several files
crack-detect photos/ --type mono --csv report.csv --overlay overlays/
```

Each image should show **one cell** (it is resized to 300x300 grey values), or, with `--module`, a whole module (see below); `--type` (`mono` or `poly`) applies to all images.

With several images, `crack-detect` checks them in parallel (`--jobs N` to limit the cores) and prints one line per image (verdict, score, file) and a summary. A file that cannot be read is reported as `ERROR` and the others are still checked (exit code 2 if any image failed, 0 otherwise).

- `--csv FILE`: a spreadsheet with one row per image: verdict, score (logistic: probability of a defect), threshold, rule, crack-length and dark-area percentiles, number of cracks, crack length and area in pixels, dark-area fraction, overlay path, error message.
- `--overlay FOLDER`: for each image, `<name>_overlay.png` (600x600) showing **why** the decision was made: cracks in **red**, dark (inactive) areas tinted **orange**, and a frame that is **green** for OK and **red** for DEFECTIVE. No matplotlib needed. Works for a single image too. The ELPV dataset is **not** needed: the package ships a small model file (`src/elpv_crack/model.json`) with both decision rules and the measurements of the healthy training cells. `python -m elpv_crack ...` works too.

From Python:

```python
from elpv_crack import Detector

result = Detector().check("cell.png", "mono")   # or a NumPy array
print(result.defective, result.score, result.features)

from elpv_crack import find_images, check_many, write_csv

rows = list(check_many(find_images(["photos/"]), "mono", overlay_dir="overlays"))
write_csv(rows, "report.csv")
```

### Whole modules: `--module`

EL images usually show a whole module, not one cell. With `--module`, `crack-detect` finds the module in the image, straightens it (perspective and tilt), counts the cell grid, cuts out every cell and checks each one:

```bash
crack-detect module.png --type mono --module                      # grid of OK / DEFECTIVE cells
crack-detect module.png --type mono --module --overlay overlays/  # + pictures
crack-detect modules/ --type poly --module --csv cells.csv        # many modules, one CSV line per cell
crack-detect module.tif --type mono --module --grid 6x10          # set the grid if it is counted wrong
crack-detect healthy_modules/ --type mono --module --save-cells cells/   # cut out cells, e.g. for crack-calibrate
```

```
Grid      : 6 x 10 cells (counted; set it with --grid if wrong)
Cells     : . = OK, X = DEFECTIVE (...)
                 1  2  3  4  5  6  7  8  9 10
              A  .  .  X  .  .  .  .  .  .  .
              B  .  .  .  .  .  .  .  X  .  .
              ...
RESULT    : DEFECTIVE: 2 of 60 cells (A3, B8)
```

Cells are named by row letter and column number (A1 is top left). `--overlay` writes `<name>_module.png` (the image with every cell tinted green or red and the found outline in blue, to check that the module and grid were found correctly) and `<name>_cells.png` (every cell's overlay in the module's layout). 16-bit images are read with their full range. If the busbars run vertically, the cells are turned 90 degrees before checking.

A module also shows what a single cell image cannot: how bright each cell is compared with the others. Cells are stretched to full contrast before checking (as the ELPV cells are), so a cell that gives no light at all would look normal on its own. In module mode, a cell less than 50 % as bright as the typical cell of its module is DEFECTIVE as a **dark cell** (CSV columns `dark_cell`, `brightness`). The 50 % is a plain choice, not fitted.

How well does it work? There are no labelled whole-module images in ELPV, so `code/module_check.py` tiles the TEST cells into 18 synthetic 6x10 modules (`code/synth_module.py`) and checks them:

| | grid found | same verdict as cell alone | AUC | accuracy | defects found | healthy passed |
|---|---|---|---|---|---|---|
| cells one by one | | | 0.853 | 0.790 | 63.4 % | 87.3 % |
| modules, straight | 18/18 | 93.5 % | 0.844 | 0.797 | 62.8 % | 88.7 % |
| modules, in perspective + rotated 4° + noise | 18/18 | 91.8 % | 0.842 | 0.791 | 63.4 % | 87.4 % |

So the module steps cost little. The changed verdicts are cells near the threshold: the single-cell detector itself changes about 3 % of its verdicts when a cell is moved by one pixel. The two threshold settings of the grid step were chosen on TRAIN modules.

Limits: the module must be completely in the image, turned by less than about 30 degrees, seen roughly from the front (opposite sides differ by less than about 20 %), and all cells of one type. Half-cut (non-square) cells are squeezed to 300x300, which the model was not built for. This was tested on synthetic modules only, not yet on real module photographs.

### Your own camera: `crack-calibrate`

The model was built from ELPV images. Images from another EL camera differ in resolution, contrast and noise, and then the balance between missed cracks and false alarms can be far off. With **images of healthy cells from your camera** (no defective ones needed; at least 20 per cell type, 100+ is better) you can calibrate it:

```bash
crack-calibrate healthy_mono/ --type mono --out my_camera.json
crack-calibrate healthy_poly/ --type poly --model my_camera.json --out my_camera.json   # optional, poly too
crack-detect photos/ --type mono --model my_camera.json
```

The percentile rule then compares cells with *your* healthy cells; the logistic rule first maps each measurement to the ELPV value at the same healthy-cell percentile. `code/calibration_check.py` tests this on the TEST half seen through simulated cameras (100 healthy cells per type to calibrate, the other 965 cells to evaluate):

| simulated camera | rule | accuracy before → after | defects found before → after | healthy flagged before → after |
|---|---|---|---|---|
| same as ELPV | logistic | 0.764 → 0.764 | 63.5 % → 63.3 % | 14.1 % → 13.9 % |
| blur + gamma + noise | logistic | 0.748 → 0.758 | 64.7 % → 57.7 % | 17.7 % → 10.8 % |
| low contrast + noise | logistic | 0.695 → **0.739** | 29.0 % → 47.9 % | 0.4 % → 6.9 % |
| low contrast + noise | percentile | 0.651 → **0.712** | 74.2 % → 53.5 % | 41.7 % → 15.7 % |

So calibration changes little when the camera is similar, and corrects a badly shifted balance when it is not. It cannot recover detail a camera does not capture: the AUC stays lower than on ELPV images.

## Folder structure

```
README.md, LICENSE   this file, license (MIT, for the code)
NOTICE               non-commercial terms of the ELPV-derived model and data
.github/workflows/   automatic tests on GitHub (tests.yml; macos.yml by hand)
pyproject.toml       package definition (pip install .) and the crack-detect command
requirements.txt     pinned Python packages for reproducing the report
src/elpv_crack/      the installable package: the method itself (see table below)
code/                research scripts: experiments, figures, tests (see table below)
data/                elpv_samples.npz: 12 example cells (the full data comes from pip)
results/             created by run_all.py (figures, tables, numbers); not stored in git
report/              report.tex / .pdf
presentation/        presentation.tex / .pdf
supplementary/       ai_usage_log.md: detailed AI-usage log (referenced in report Sec. 6)
```

**The package** (`src/elpv_crack/`, what `pip install .` installs):

| file | role |
|---|---|
| `params.py` | every pipeline parameter and the random seed |
| `preprocess.py` | percentile normalisation, valid-region mask, noise |
| `busbar.py` | busbar detection (row-mean profile) and filling (cubic, linear, smoothing spline) |
| `edges.py` | own Gaussian convolution, 5-point Laplacian, LoG; Sobel and Canny baselines |
| `clustering.py` | DBSCAN, elongation filter (covariance eigenvalues), features |
| `measures.py` | the extra measurements of the logistic rule (dim/dead area, line responses) |
| `pipeline.py` | per-cell pipeline and parallel driver |
| `scoring.py` | both decision rules (percentile, logistic) and the model file |
| `detector.py` | `Detector`: reads an image, runs the pipeline, scores it, decides |
| `batch.py` | many images: finds them, checks them in parallel, writes the CSV report |
| `viz.py` | overlay picture (cracks + dark area + verdict frame); module pictures; figure of all stages (needs matplotlib) |
| `module.py` | whole modules: outline, straightening, cell grid, dark cells, checking every cell |
| `cli.py` | the `crack-detect` command |
| `calibrate.py` | the `crack-calibrate` command: calibration with healthy cells from another camera |
| `model.json` | the bundled model, built by `code/build_model.py` |

**The research scripts** (`code/`, need the ELPV dataset, see "How to run"):

| file | role |
|---|---|
| `config.py` | paths, label definition, subset size |
| `data.py` | loads ELPV, label definition, stratified subsets, saves samples |
| `evaluate.py` | percentile scores, threshold, metrics, bootstrap CI |
| `experiments.py` | experiments E1–E6 (figures and tables) |
| `run_all.py` | runs everything and writes `results/` (`--quick`, `--help`) |
| `select_features.py` | chooses the measurements of the logistic rule (forward selection, CV on TRAIN) |
| `build_model.py` | writes `src/elpv_crack/model.json` from the TRAIN half; `--evaluate` compares both rules on TEST |
| `calibration_check.py` | tests calibration with simulated cameras on the TEST half |
| `synth_module.py` | synthetic module images built from cells (for module mode) |
| `module_check.py` | tests module mode on synthetic modules of TEST cells |
| `benchmark_data.py` | downloads a second, independent benchmark of labelled EL cells (not stored in git) |
| `benchmark_check.py` | tests the detector on those cells, with the ELPV model and calibrated per source |
| `detect.py` | checks one ELPV cell by index and compares with the expert label (`--method`) |
| `test_numerics.py` | 16 unit tests of the numerical building blocks on synthetic data with known answers |
| `test_package.py` | 20 tests of the package: bundled model, scores of the sample cells (both rules), calibration, image input, batch mode, CSV, overlays, command line |
| `test_module.py` | 12 tests of module mode on synthetic modules: grid, perspective, 16-bit, vertical busbars, dead cells, command line |

## Environment

- Python 3.14.10, Fedora Linux 44, AMD Ryzen 7 250 (8 cores / 16 threads), 16 GB RAM
- Packages: see `requirements.txt`. The ELPV images are included in the `elpv-dataset` pip package (Buerhop-Lutz et al., 2018), so no separate download is needed.

## How to run

```bash
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt        # also installs the ELPV images and this package

cd code
python run_all.py          # reproduces every figure, table and number of the report (about 4-5 min)
python run_all.py --quick  # same without the E6 sensitivity sweeps (about 1 min)
python detect.py 385       # check one cell and explain every step (a few seconds)
python test_numerics.py    # unit tests, e.g. stencil exact on quadratics, error O(h^2) (2 s)
python test_package.py     # tests of the installed package and the crack-detect command (about 15 s)
python test_module.py      # tests of module mode (about 10 s)
python module_check.py     # module mode on synthetic modules of TEST cells (about 1 min)
python select_features.py  # how the measurements of the logistic rule were chosen (about 1 min)
python build_model.py --evaluate   # rebuild the bundled model and compare both rules on TEST (about 1 min)
python benchmark_data.py   # once: download the second benchmark (about 130 MB)
python benchmark_check.py  # the detector on cells from four other sources (about 15 s)
```

The test files also run automatically on GitHub for every push and pull request (`.github/workflows/tests.yml`): Python 3.10, 3.12 and 3.14 on Linux, 3.14 on Windows, and once with the oldest package versions `pyproject.toml` allows; always from a normal `pip install .` without matplotlib. The same tests on macOS (`.github/workflows/macos.yml`) are started by hand, because GitHub often has no free macOS runner.

Every script explains itself with `--help`. Optional: `python data.py` prints dataset statistics and writes `data/elpv_samples.npz`.

### Checking a single ELPV cell: `detect.py`

`detect.py` uses the same code and model as `crack-detect`, runs the pipeline on one cell and prints each step: busbars found, LoG candidate pixels, DBSCAN clusters, the two features, their percentiles among the healthy TRAIN cells of the same type, the score, the threshold, the decision and, for ELPV cells, the expert label. A figure of the five stages is saved to `detect_output/`.

```bash
python detect.py 385                           # cracked mono cell (TEST half)  -> DEFECTIVE
python detect.py 59                            # healthy mono cell (TEST half)  -> OK
python detect.py --image my_cell.png --type poly   # your own image (resized to 300x300)
```

It uses the bundled model, so its scores are exactly those of experiment E3.

### Cells from other cameras: `benchmark_check.py`

All the numbers above are on ELPV cells. To see how the detector does on cells from other cameras and labs, `benchmark_check.py` uses the EL benchmark of Pratt et al. (2023): 527 cells from four sources that are not ELPV, with hand-drawn defect masks. A cell counts as defective if its mask marks a crack or an inactive area.

```bash
python benchmark_data.py    # once: downloads about 130 MB to data/benchmark_el/
python benchmark_check.py   # about 15 s
```

The benchmark's repository states no license, so its images are only downloaded for local use and never stored in git.

Each benchmark image shows a cell with parts of its neighbours, so each cell is cut out from the mask first, and only the mask inside the cell counts for its label. Cells with vertical busbars are turned 90 degrees with the same test that `crack-detect --module` uses.

| all 527 cells (99 defective) | AUC | defects found | healthy cells flagged |
|---|---|---|---|
| ELPV model, logistic | 0.64 | 72% | 50% |
| ELPV model, percentile | 0.68 | 88% | 55% |
| calibrated per source, logistic | 0.69 | 42% | 18% |
| calibrated per source, percentile | 0.72 | 45% | 20% |

"Calibrated" means `crack-calibrate` with healthy cells of the same source. Each half of the source's modules is scored by a calibration made from the other half, so no cell is scored by a calibration that used it.

What this shows:

- **The ELPV model does not carry over to other cameras.** On these cells it flags half of the healthy cells. Calibrating with healthy cells from the same camera is needed.
- **Results depend strongly on the cells.** After calibration the AUC is 0.81 on CFVS (mostly mono cells) and up to 0.71 on CSIR. On ARTS it is no better than chance (0.47–0.56): those poly cells have 5–6 busbars and dark grain patterns, which the detector takes for cracks. SDLE has only 18 cells, too few to judge.
- **Small cracks are often missed.** With the ELPV model, 89% of the largest third of cracks are found, but only about 56% of the smaller two thirds.
- **The busbar test of module mode misses some single cells.** It needs clear evidence before turning a cell. Turning every cell whose busbars run down would raise the calibrated AUC from 0.72 to 0.75 (percentile rule), tested on these cells.

The detector is built for ELPV-like cells: 2–4 busbars and an even surface. On modern cells with many busbars, or on poly cells with strong grain, treat its results with care, even after calibration.

### Rebuilding the PDFs

The report uses the figures and tables in `results/`, so run `python run_all.py` first. Then, with TeX Live and `latexmk`, from the project root:

```bash
(cd report       && latexmk -pdf report.tex)
(cd presentation && latexmk -pdf presentation.tex)
```

## Expected output and run time

`run_all.py` first prints what the program does and the dataset split. Then, for each step, it prints one line saying what is computed, one line with the key result and the time taken. At the end it lists where everything was written. The printed text is also saved to `results/run_log.txt`. On the laptop above a full run takes about 4–5 minutes (last run: 4 min 31 s; it varies with machine load), well under the 10-minute limit:

| step | time |
|---|---|
| E1 finite differences, E2 interpolation, figures | ≈ 4 s |
| E3 main evaluation (all 2,624 cells) | ≈ 13–16 s |
| E4 detector comparison | ≈ 25–35 s |
| E5 float32 vs float64 | ≈ 7–8 s |
| E6 sensitivity sweeps (800-cell subset, 48 pipeline runs, with a progress counter) | ≈ 140–210 s |

The pipeline uses all cores through joblib; to change that, set `N_JOBS` in `src/elpv_crack/params.py`.

Outputs (written to `results/`, which is not stored in git; run `run_all.py` to create it, also needed before rebuilding the report PDF):
- `results/figures/`: `pipeline.png`, `busbar_example.png`, `interp_error.png`, `fd_error.png`, `roc.png`, `detectors.png`, `sensitivity.png`
- `results/tables/`: one `.csv` and one `.tex` file per table (the report `\input`s the `.tex` files directly), plus `features_all_cells.npz` with the features and score of every cell
- `results/summary.json`: every number quoted in the report

Key expected numbers (held-out test half, 1,165 cells):
- **AUC = 0.797** (95% CI 0.77–0.82)
- accuracy 0.782, precision 0.743, recall 0.584

## Reproducibility

- A single seed (`SEED = 0` in `src/elpv_crack/params.py`) drives the train/test split, the subsets, the hidden rows in E2, the added noise and the bootstrap.
- DBSCAN, the LoG and the splines are deterministic.
- Results do not depend on the number of parallel workers: cells are processed independently, and noise is seeded per cell.
- Parameters marked "(tuned on TRAIN)" in `src/elpv_crack/params.py` were chosen using only the training half.

## License

**elpv-crack is for non-commercial use.** The detector needs a model to run, and the only model available is derived from the ELPV dataset (CC BY-NC-SA 4.0). Details are in [`NOTICE`](https://github.com/giorgimskh/elpv-crack-detection/blob/main/NOTICE).

- **Code** (`src/`, `code/`), report and slides: [MIT License](https://github.com/giorgimskh/elpv-crack-detection/blob/main/LICENSE).
- **The bundled model** (`src/elpv_crack/model.json`) holds measurements of healthy ELPV cells, and its decision rules were fitted on ELPV cells and their labels, so it is covered by the dataset license: [CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/) (no commercial use; share what you build from it under the same license). **Calibrated models** made by `crack-calibrate` keep the ELPV reference and rules, so the same license applies to them.
- **ELPV images** (`data/elpv_samples.npz`, and the images in the figures `run_all.py` creates) come from the ELPV dataset by Buerhop-Lutz et al. and Deitsch et al. and stay under CC BY-NC-SA 4.0. The full dataset is installed through the `elpv-dataset` pip package.

Commercial use would need permission from the dataset's rights holders, or a model built entirely from your own images. This is not legal advice.

If you use the dataset, please cite:

- C. Buerhop-Lutz et al., "A benchmark for visual identification of defective solar cells in electroluminescence imagery," 35th EU PVSEC, 2018.
- S. Deitsch et al., "Automatic classification of defective photovoltaic module cells in electroluminescence images," Solar Energy 185:455–468, 2019.

The benchmark used by `benchmark_check.py` (downloaded separately, not part of this project):

- L. Pratt, J. Mattheus, R. Klein, "A benchmark dataset for defect detection and classification in electroluminescence images of PV modules using semantic segmentation," Systems and Soft Computing 5:200048, 2023.
