AI and ML Network Blog

Manufacturing Defect & Surface Anomaly Segmentation Guidelines for AOI

Build accurate industrial AOI defect segmentation datasets for PCBs, metal, and packaging. Master cosmetic vs critical rules, hairline cracks, and SAHI.

October 27, 2026 Updated November 25, 2026 Onidul Islam Siyam Onidul Islam Siyam 11 min read Advanced
Manufacturing AI Defect Segmentation AOI Inspection Semantic Segmentation Data QA

The Short Answer

Industrial Automated Optical Inspection (AOI) models for PCB solder joints, machined metal, textiles, and packaging lines rarely fail because of backbone architecture—they fail because annotation guidelines blur the line between acceptable cosmetic variation and reject-grade critical defects. Building a factory-ready defect segmentation dataset requires choosing the right pixel primitive (brush masks for sub-5-pixel hairline cracks, tight polygons for area flaws), annotating full-resolution images before SAHI/patch tiling, filtering clipped border fragments mathematically, and managing 1:200+ rare-defect class imbalance without leaking false overkill onto the production line.

Separating Cosmetic Variations from Reject-Grade Critical Defects

In consumer vision, a slightly noisy class definition drops validation mAP by a few points. On a high-speed manufacturing conveyor, ambiguous defect labeling creates two direct financial liabilities:

  • False Escapes (Underkill): Missing a true PCB solder bridge, battery-cell dent, or sterile-seal puncture lets defective units reach customers, triggering costly recalls and SLA penalties.
  • False Rejects (Overkill): Labeling harmless machining brush marks, acceptable flux residue, or minor mold-release scuffs as defects trains the model to scrap good inventory—forcing plant managers to shut down the AI system within a week.

Never hand raw factory photos to general-purpose annotators and say “label every flaw.” Build a 3-Tier Defect Tolerance Standard signed off by your plant QA lead before batch 1 starts:

  1. Critical / Reject-Grade Defect Classes (reject_*): Quantified strictly by physical unit tolerance (e.g., crack length >= 1.5 mm, solder bridge spanning two distinct copper pads, pinhole exposing substrate).
  2. Cosmetic Acceptable Variations (cosmetic_ok or explicit negative): Real surface quirks—light anodized streaks, harmless ink smudges, acceptable die marks—that look anomalous to a neural network. Pro tip: Explicitly labeling frequent cosmetic artifacts as a dedicated non-reject auxiliary class (cosmetic_pass) often cuts production overkill dramatically compared to silently leaving them unlabeled as background.
  3. Inspection Ignore Zones (ignore_mask): Clamps, fixture jigs, laser serial numbers, reflections outside the part boundary, and conveyor belts masked out globally so loss gradients never chase fixture wear.

Choosing the Right Geometry: Brush Masks vs. Polygons vs. Boxes

Selecting the wrong annotation primitive cripples model convergence before training even begins. A diagonal 3-pixel scratch spanning 200 pixels across brushed aluminum fills less than 2% of its axis-aligned bounding box—meaning 98% of pixels inside the box are completely healthy metal!

Match your defect archetype directly to the optimal semantic segmentation or detection geometry:

Industrial Defect ArchetypeRecommended Annotation PrimitiveBoundary Tolerance PolicyWhy Blind Auto-Labeling (e.g., SAM2) Struggles
Sub-5px Hairline Cracks & Micro-ScratchesRaster Brush Mask (1–4 px tip) or centerline polyline dilated to fixed widthTrace full continuous path; enforce consistent 2–3 px minimum stroke width across annotatorsFaint 1-pixel contrast disappears into brushed metal grain; SAM2 fragments lines into broken dots
PCB Solder Bridges, Tombstoning & Missing PadsTight Polygon (bridges/solder) or OBB / Tight Box (shifted/missing components)Follow exact copper/solder meniscus boundary; exclude specular LED glare ringsHigh metallic reflections split single solder blobs or fuse neighboring pins
Metal Pitting, Corrosion, Oil Stains & DelaminationPixel Brush / Freehand Mask with interior holes preservedCapture diffuse transition zone at an agreed visual threshold (golden visual card)No crisp edge gradient; SAM2 leaks across the entire metal plate
Textile Snags, Missing Weft & Fabric HolesPixel Mask (snags/holes) + Tight Polygon (weave blotches)Separate structural yarn breaks from loose surface lint using lighting-angle referencesRepetitive weave texture triggers massive mask hallucination
Packaging Seal Wrinkles, Dents & Label TearsTight Polygon (tears/wrinkles) or Instance Mask (overlapping dents)Label functional seal-channel compromises separately from harmless outer-margin creasesTranslucent film reflections mimic wrinkle highlights

For teams evaluating hybrid pre-labeling pipelines on industrial imagery, review our engineering breakdown of SAM2 auto-labeling vs. human-in-the-loop QA before committing auto-masks to your validation split.

Handling Sub-5-Pixel Hairline Cracks Without Mask Collapse

Standard segmentation metrics like pixel IoU break brutally on thin industrial cracks and micro-scratches. Consider a 2 px wide crack: if a human annotator traces it just 1 pixel to the left of your model’s predicted mask, pixel IoU plummets from 1.00 down to 0.33—even though the detector localized the defect accurately!

Follow four strict engineering rules for sub-5-pixel anomalies:

  1. Enforce Standardized Minimum Brush Width: Never let Annotator A trace cracks at 1 px while Annotator B paints them at 6 px. Standardize a crisp pixel stroke width (typically 2 px or 3 px on native high-res sensors) so Dice and Focal-Tversky losses see uniform foreground width distribution.
  2. Trace Continuous Paths Through Faint Micro-Gaps: If lighting glare momentarily fades a continuous hairline fracture for 4 pixels, bridge the path cleanly according to physical crack continuity rather than splitting one physical fracture into five disconnected specks.
  3. Preserve Topological Holes: On hollow defects (blistered coating rings, annular delamination, washer burrs), ensure your export format supports interior polygon holes or lossless PNG mask indexing—not convex-hull polygons that swallow healthy interior metal.
  4. Evaluate with Boundary F1 / Dilated Tolerance Dice alongside Pixel IoU: Track defect-level recall (did we catch every physical reject unit?) plus a ±2 px tolerance Boundary F1 score so slight annotator click variance does not mask real model gains.

High-Resolution Tiling (SAHI / Patch Cropping) Without Border Artifacts

Factory line-scan and AOI cameras routinely shoot at 4K to 20MP (4096×3000 or higher). Downsizing a 12MP PCB photo to 640×640 erases every 4-pixel solder bridge instantly, so production pipelines slice images into overlapping tiles (512×512 or 1024×1024) using SAHI (Slicing Aided Hyper Inference) or custom sliding windows.

Here is the single biggest workflow mistake manufacturing AI teams make: tiling raw images first and handing disconnected patches to annotators.

Workflow DimensionAnnotate Full-Res First, Then Tile Programmatically (Recommended)Tile Raw Images First, Then Annotate Disconnected Patches (Anti-Pattern)
Spatial & Part ContextAnnotator sees full PCB board, part orientation, and lighting gradient—preventing fixture/shadow misreadsAnnotator stares at zoomed abstract gray squares and frequently labels normal edges as defects
Border-Splitting ConsistencyOne unified ground-truth mask spans the defect cleanly; tiling script slices and filters slivers deterministicallyAnnotators label the defect differently across adjacent overlapping tiles, injecting contradictory supervision
Retiling FlexibilityRe-generate 512px, 768px, or 1024px tiles with any overlap ratio in seconds with zero re-labeling costChanging tile size or overlap requires painful coordinate stitching or re-annotating from scratch
Negative Tile SamplingProgrammatically sample hard-negative healthy tiles around part edges & solder pads cleanlyWastes human hours scrolling through thousands of empty blank background tiles

Python Pipeline: Tiling Full-Res Defect Masks Safely with Border Filtering

When slicing full-resolution AOI images and integer class-index PNG masks (0 = background, 1..N = defect classes) into overlapping training patches, never blindly keep every tile containing 3 clipped edge pixels of a defect. Tiny border slivers (< 15% of the defect’s area or < 16 px total) teach your segmentation head to hallucinate false defects along every tile margin.

Use this deterministic Python tiling snippet to generate clean overlapping patches, reject clipped edge slivers, and cap healthy negative background tiles to stabilize class ratios:

from pathlib import Path
import random
import numpy as np
from PIL import Image


def tile_image_and_mask(
    img_path: Path,
    mask_path: Path,
    out_img_dir: Path,
    out_mask_dir: Path,
    tile_size: int = 512,
    overlap: float = 0.25,
    min_defect_px: int = 20,
    min_border_keep_ratio: float = 0.15,
    neg_keep_prob: float = 0.15,
):
    img = np.array(Image.open(img_path).convert("RGB"))
    mask = np.array(Image.open(mask_path))  # uint8 class indices
    h, w = mask.shape
    stride = int(tile_size * (1.0 - overlap))
    out_img_dir.mkdir(parents=True, exist_ok=True)
    out_mask_dir.mkdir(parents=True, exist_ok=True)

    ys = sorted(set(list(range(0, max(1, h - tile_size + 1), stride)) + [max(0, h - tile_size)]))
    xs = sorted(set(list(range(0, max(1, w - tile_size + 1), stride)) + [max(0, w - tile_size)]))
    saved_pos = saved_neg = skipped = 0

    for y in ys:
        for x in xs:
            img_tile = img[y : y + tile_size, x : x + tile_size]
            mask_tile = mask[y : y + tile_size, x : x + tile_size]
            defect_px = int((mask_tile > 0).sum())

            if defect_px == 0:
                if random.random() > neg_keep_prob:
                    continue
                saved_neg += 1
            else:
                on_border = (
                    (mask_tile[0, :] > 0).any() or (mask_tile[-1, :] > 0).any()
                    or (mask_tile[:, 0] > 0).any() or (mask_tile[:, -1] > 0).any()
                )
                y0, y1 = max(0, y - 64), min(h, y + tile_size + 64)
                x0, x1 = max(0, x - 64), min(w, x + tile_size + 64)
                local_px = int((mask[y0:y1, x0:x1] > 0).sum())

                # Drop tiny clipped defect slivers touching tile borders
                if on_border and (defect_px < min_defect_px or (local_px > 0 and defect_px / local_px < min_border_keep_ratio)):
                    skipped += 1
                    continue
                saved_pos += 1

            stem = f"{img_path.stem}_y{y}_x{x}"
            Image.fromarray(img_tile).save(out_img_dir / f"{stem}.png")
            Image.fromarray(mask_tile.astype(np.uint8)).save(out_mask_dir / f"{stem}.png")

    return {"pos_tiles": saved_pos, "neg_tiles": saved_neg, "skipped_slivers": skipped}


if __name__ == "__main__":
    print(tile_image_and_mask(Path("raw/pcb_042.png"), Path("masks/pcb_042.png"), Path("tiled/images"), Path("tiled/masks")))

Tuning neg_keep_prob balances healthy background ratios cleanly while preserving hard-negative variety across solder pads, silkscreen text, and edges.

Surviving 1:500 Class Imbalance and Passing Factory QA Audits

On high-yield lines running at 99.5% yield, defect scarcity magnifies every error: if a rare defect class has 60 real instances, just 6 mislabeled masks corrupt 10% of its entire supervision. Stabilize rare-defect performance with three rules:

  1. 100% Dual-Pass Senior QA on Every Positive Defect Frame: Sampled QA fails when positive defects occur in < 1% of units. Manually verify every positive defect mask, and reserve random sampling strictly for checking missed subtle flaws in healthy frames.
  2. Stratify Splits by Production Lot, Shift, and Camera Head: Group validation splits by production day or machine line—never random shuffling—so offline metrics reflect real lighting drift, tool wear, and raw material variance.
  3. Combine Clean Masks with Imbalance-Aware Losses: Pair verified minority masks with Focal-Tversky or Lovász-Softmax losses; see our deep dive on handling class imbalance in computer vision datasets.

Our dedicated image annotation workflows support full-resolution AOI pipelines natively inside CVAT, Supervisely, Encord, Roboflow, and Label Studio with lossless mask exports.

Calibrate Your AOI Defect Taxonomy Before Scaling

Industrial defect segmentation rewards precision over raw headcount: a tightly audited dataset of 1,500 verified defect parts with strict cosmetic-vs-critical boundaries routinely outperforms 25,000 loosely painted masks. At AI and ML Network, our QA-led specialists work inside your private workspace under strict NDA—protecting proprietary PCB layouts, part CAD appearances, and factory imagery while aligning directly with your quality engineers.

Start with a 100-to-250-image calibration pilot covering your hardest rare anomalies, hairline scratches, and borderline cosmetic marks to lock down mask thickness, pixel agreement, and SAHI tiling compatibility before scaling. Share your camera resolution, defect classes, and target platform via our project scoping form or contact our team directly on our contact page.

Frequently Asked Questions

How do you separate acceptable cosmetic marks from reject-grade critical defects during annotation? +

Co-author a golden-sample defect taxonomy directly with factory quality engineers before labeling begins. Define measurable thresholds—such as scratch length in millimeters, solder bridge electrical clearance, or stain contrast delta—and assign borderline acceptable marks to an explicit cosmetic_pass class or strict ignore rule instead of dumping them into reject classes.

Should sub-5-pixel hairline cracks be labeled with polygons, brush masks, or bounding boxes? +

Use pixel-exact brush masks or high-density raster bitmaps with a standardized minimum stroke width (commonly 2 to 4 pixels) rather than loose bounding boxes or coarse polygons. Bounding boxes drown thin diagonal cracks in 95 percent healthy background pixels, starving segmentation and detection losses of signal.

Should we tile high-resolution 4K or 12MP AOI images before or after human annotation? +

Always annotate defects on full-resolution calibrated source images first, then run deterministic overlapping patch tiling (SAHI or custom sliding windows) programmatically afterward. Asking annotators to label pre-cropped tiles strips away spatial context, causing severe boundary disagreement on defects that cross tile seams.

Why does blind SAM2 auto-labeling fail on industrial surface anomalies? +

SAM2 relies on natural-image luminance contrast and clear objectness priors. Industrial micro-scratches, matte-metal oxidation, solder cold joints, and translucent packaging seal wrinkles exhibit faint texture contrast and irregular diffuse boundaries—causing blind SAM2 masks to miss defects completely or bleed into normal machining grain.

Work With AI and ML Network

Need help with annotation, QA, or AI model evaluation?

Share your dataset, model objective, or evaluation criteria. We work inside your preferred platform and scope a clear pilot before production.