microdefectcv

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


MicroDefectCV

MicroDefectCV is a computer vision toolkit for defect detection in perovskite solar cell SEM images.

PyPI

https://pypi.org/project/microdefectcv/

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


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


License

MIT β€” see LICENSE.