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.

PyPI version PyPI Downloads License: MIT Python 3.8+

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
  • 💻 CLI entry point — run microdefectcv directly from any terminal after install

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)

After pip install microdefectcv, the microdefectcv command is available from any terminal — no need to navigate to a script folder.

# Auto-detect mode
microdefectcv "C:\Users\asus\Desktop\SEM annotation\3D perovskite with PbI2 excess\08-10.tif" --mode auto --min-area 20

# PbI2 bright particle + needle detection
microdefectcv "C:\Users\asus\Desktop\SEM annotation\3D perovskite with PbI2 excess\08-10.tif" --mode pbi2 --min-area 30

# Pinhole / dark void detection
microdefectcv "C:\Users\asus\Desktop\SEM annotation\3D perovskite with PbI2 excess\08-10.tif" --mode pinhole --min-area 20

# 2D perovskite (flat morphology)
microdefectcv "C:\Users\asus\Desktop\SEM annotation\3D perovskite with PbI2 excess\08-10.tif" --mode 2d --min-area 20

# 3D perovskite with grain boundary suppression
microdefectcv "C:\Users\asus\Desktop\SEM annotation\3D perovskite with PbI2 excess\08-10.tif" --mode 3d --min-area 20

# Mixed 2D-3D morphology
microdefectcv "C:\Users\asus\Desktop\SEM annotation\3D perovskite with PbI2 excess\08-10.tif" --mode 3d_2d --min-area 20

Method 2: Batch Processing (PowerShell)

Process an entire folder of images automatically:

Get-ChildItem -Path "path\to\folder" -Filter *.jpg | ForEach-Object {
    microdefectcv $_.FullName --mode auto
}

Method 3: Python API

Import and use 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.1.tar.gz (20.7 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.1-py3-none-any.whl (19.1 kB view details)

Uploaded Python 3

File details

Details for the file microdefectcv-0.1.1.tar.gz.

File metadata

  • Download URL: microdefectcv-0.1.1.tar.gz
  • Upload date:
  • Size: 20.7 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.1.tar.gz
Algorithm Hash digest
SHA256 1419ae87b830b26e169a55297baedd1bf286b57ed1c32c86eaea86f293f066f8
MD5 e1bab16b8a67e52ac291ce80f51ae2b4
BLAKE2b-256 4f127c3f6855e3e0a3f5134e0440f48a5b505bc135d8309c2d64355afa33b133

See more details on using hashes here.

File details

Details for the file microdefectcv-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: microdefectcv-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 19.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.11

File hashes

Hashes for microdefectcv-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 088cc8e5cf40a3f409a42bc368b6c0fc43ef2bd387755e028ce68e356265c9f4
MD5 ff6428e45b55f43517b6b213e402ddd6
BLAKE2b-256 0a625c2bed007912feaec4e66f51a316524144f30b4cc8c004ab983bf8b6fbb5

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