Skip to main content

Adaptive OpenCV-based defect enhancement and segmentation for SEM and microstructure images

Project description

MicroDefectCV

Adaptive OpenCV-based defect enhancement and segmentation for SEM and microstructure images.

A domain-specific computer vision toolkit for defect detection in perovskite solar cell SEM images. MicroDefectCV provides a reusable, mode-aware pipeline for pinhole and PbI₂ bright-particle detection that generalises to a wide range of microstructure images — no deep learning or labelled data required.

This package provides a lightweight classical computer vision baseline for defect enhancement and segmentation. It does not claim to replace deep learning methods on large annotated datasets.


Features

  • 🔬 Six detection modes covering different perovskite morphologies and defect types
  • 🧠 Auto mode that classifies image morphology from statistics alone
  • 🧩 Grain boundary suppression for 3D and mixed-morphology images
  • 📐 Needle crystal detection for elongated PbI₂ excess structures
  • 📊 Defect statistics (count, area, area ratio) in one call
  • 🖼️ Intermediate stage images for debugging and research
  • Zero deep learning — pure OpenCV + NumPy, runs on CPU
  • 📦 Pip-installable clean package structure

Installation

pip install microdefectcv

Or install from source:

git clone https://github.com/Sahilsonii/microdefectcv.git
cd microdefectcv
pip install -e .

Quick Start

import cv2
from microdefectcv import detect_defects

image = cv2.imread("sample_images/sem_image.png")

result = detect_defects(
    image,
    mode="auto",       # auto-selects morphology from image statistics
    min_area=20,
    return_intermediate=True
)

print(f"Defects found  : {result['defect_count']}")
print(f"Area ratio     : {result['defect_area_ratio']:.4f}")

mask     = result["mask"]         # binary defect mask
enhanced = result["enhanced"]     # CLAHE-enhanced image
contours = result["contours"]     # list of OpenCV contours

Detection Modes

Mode Target Defects Image Morphology
auto All Auto-detected from statistics
pbi2 PbI₂ bright particles + needles Any
pinhole Dark pinholes (small + large) Any
2d Both 2D perovskite (flat morphology)
3d Both + needles 3D perovskite (grain suppression active)
3d_2d Both + needles Mixed 2D-3D morphology

Method Pipeline

Input Image
    │
    ├─ Grayscale conversion (if BGR)
    ├─ SEM metadata bar removal
    ├─ Mode selection (auto or user-specified)
    ├─ Gaussian denoising + CLAHE
    │
    ├─ [3D / 3D-2D only] Grain boundary suppression mask
    │
    ├─ Bright particle detection (Top-Hat + dual percentile threshold)
    ├─ Dark pit detection       (Percentile threshold + micro-threshold)
    ├─ Needle crystal detection (Rectangular Top-Hat + aspect ratio filter)
    │
    ├─ Shape feature filtering (area, circularity, solidity, contrast)
    ├─ Non-maximum suppression (IoU-based)
    │
    └─ Output: mask, enhanced, contours, defect_count, defect_area_ratio

See docs/method_overview.md for full technical details.


Parameters

Parameter Type Default Description
image np.ndarray Grayscale or BGR uint8 image
mode str "auto" Detection mode (see table above)
sensitivity float 1.5 Sensitivity hint (reserved for tuning)
min_area float 20 Minimum defect area in pixels
return_intermediate bool False Include per-stage pipeline images

Quick Start Guide

Method 1: Command Line (Single Image)

Process a single image and generate a pipeline grid + YOLO annotations in the outputs/ folder.

# Auto-detect mode
python examples/demo_perovskite_sem.py path/to/image.jpg

# Force PbI2 mode and drop minimum area to catch tiny sand-like particles
python examples/demo_perovskite_sem.py path/to/image.jpg --mode pbi2 --min-area 3

Method 2: Batch Processing (PowerShell)

Process an entire folder of images automatically:

Get-ChildItem -Path "path\to\folder" -Filter *.jpg | ForEach-Object {
    python examples/demo_perovskite_sem.py $_.FullName --mode auto
}

Method 3: Python API

Import and use the standalone pip package directly in your own scripts:

import cv2
from microdefectcv import detect_defects
from microdefectcv.visualization import save_yolo_annotations

image = cv2.imread("path/to/image.jpg")
result = detect_defects(image, mode="auto", min_area=20)

print(f"Found {result['defect_count']} defects!")
save_yolo_annotations(result["detections"], image.shape, "outputs/labels.txt")

Results

Defect Detection Output


Comparison

Method Suitability Notes
Global Threshold Low Fails under uneven SEM lighting
Otsu Low–Medium No domain adaptation
CLAHE + Otsu Medium Better contrast, still single-class
Canny Edge-only Not suitable for void/particle detection
MicroDefectCV High Adaptive, mode-aware, domain-specific

Running Tests

pytest

Use Cases

  • Perovskite solar-cell SEM — pinhole and PbI₂ crystal detection
  • Thin-film defect inspection — dark voids and bright particle segmentation
  • Microstructure void detection — general SEM / optical microscopy
  • Coating and surface QC — surface dark defect segmentation
  • Classical CV baseline — compare against DL models on annotated datasets

Citation

If you use MicroDefectCV in academic work, please cite:

@software{microdefectcv2025,
  title  = {MicroDefectCV: Adaptive OpenCV-based Defect Segmentation for SEM Images},
  author = {Sahil Soni},
  year   = {2025},
  url    = {https://github.com/Sahilsonii/microdefectcv}
}

Roadmap

  • Annotated SEM benchmark dataset
  • scripts/evaluate.py evaluation script
  • Hyperparameter search / sensitivity analysis
  • Optional integration with OpenCV-contrib

License

MIT — see LICENSE.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

microdefectcv-0.1.0.post1.tar.gz (19.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

microdefectcv-0.1.0.post1-py3-none-any.whl (17.2 kB view details)

Uploaded Python 3

File details

Details for the file microdefectcv-0.1.0.post1.tar.gz.

File metadata

  • Download URL: microdefectcv-0.1.0.post1.tar.gz
  • Upload date:
  • Size: 19.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.11

File hashes

Hashes for microdefectcv-0.1.0.post1.tar.gz
Algorithm Hash digest
SHA256 2f0b018da9a328708410d92104d90820f8dd7365b8f0b509bb2c67fe3ee65394
MD5 e8ce2804c377dc2c3ae73731f36703d4
BLAKE2b-256 53511c0e36d6033b3657a2b5da5356ed16c85c0e5e9a2cfcec595565d47b85b1

See more details on using hashes here.

File details

Details for the file microdefectcv-0.1.0.post1-py3-none-any.whl.

File metadata

File hashes

Hashes for microdefectcv-0.1.0.post1-py3-none-any.whl
Algorithm Hash digest
SHA256 7a9fa0055f6ab28a2cc4b658b9c84c9bc32602d7c8d365fe8297f190e8011247
MD5 9a634325301843f92e39b8d015f5d1a8
BLAKE2b-256 d1f9bd50d03a74020c0ff24e2646908a6697131d089cd3c582c1fd1ae422e3a8

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page