Some original image labels are retained; figure captions and explanations are provided in English.

PART V · DEEP LEARNING

What Is Image Segmentation? Semantic, Instance and Panoptic Segmentation

Semantic, instance and panoptic outputs are distinguished before examining U-Net, DeepLab, Mask R-CNN and Mask2Former. Missing-coating and defect-area examples show the influence of annotation boundaries, input resolution and post-processing. IoU, Dice and boundary metrics are compared, followed by the additional geometry needed to turn a mask into physical area and an acceptance decision.

Article sectionsWhat is image segmentation?The difference between semantic, instance and panoptic segmentationWhy is annotation engineering critical?What does the U-Net architecture solve?Why are DeepLab and atrous convolution important?Instance segmentation with Mask R-CNNMask2Former and the mask classification approachIoU, Dice and boundary metricsA pixel mask is not a physical measurementWhy do fine scratches require specialized design?Post-processing applied to masksHow are quality decisions made from segmentation output?Subgroups for error analysisApplication example: missing paint coverageWhich approach suits which task?How do we define annotation boundaries in segmentation?Mask pixel resolution and loss calculationHow should boundary metrics and physical tolerances be interpreted together?Instance segmentation and object-count consistencyWhen does a two-stage quality system make sense?Frequently asked questionsImage sources

U-Net, DeepLab, Mask R-CNN, Mask2Former, fine-defect masks, boundary precision and segmentation design. This guide examines the assumptions behind the method, the conditions in which it can be used, its failure modes and the decisions involved in field deployment.

What is image segmentation?

Short answer: Segmentation is the problem of assigning image pixels to semantic classes or specific object instances. While classification produces a single label and object detection produces boxes, segmentation can show the pixel-level area of an object or defect. This is valuable for measurements such as scratch length, paint overflow, weld seam geometry and the proportion of a surface covered by defects. However, a model mask is not automatically an accurate measurement in millimeters; calibration and uncertainty analysis are required.

A segmentation algorithm often outputs a matrix of class scores at the same resolution as the image or a related resolution. These scores are thresholded to obtain a binary mask. However, post-processing such as thresholding, merging small regions and filling holes can substantially affect the result. The entire mask generation pipeline must be the same in experiments and in deployment.

Three types of segmentationThe scope of semantic, instance and panoptic outputssemanticinstancepanopticoutputConceptual technical diagram · Not an architectural drawing to scale
Original diagram: The scope of semantic, instance and panoptic outputs

The difference between semantic, instance and panoptic segmentation

Semantic segmentation assigns a class label to every pixel. If two bolts of the same type are side by side, both may remain within the same class region. Instance segmentation separates different object instances of the same class. Panoptic segmentation handles both countable object instances and the semantic classes of amorphous regions, such as the background, in a shared output structure.

In industrial use, semantic segmentation is often useful when a single defect mask is sufficient. If a photograph contains three separate scratches that must be counted individually, instance segmentation or component analysis is needed. The panoptic approach makes sense when a scene requires both material/ground classes and object identity. Presenting these as merely different names overlooks their output requirements.

A mask's pixel-level class accuracy is not the same as the actual object count. Two touching objects may merge into one mask, leaving the total defect area close to correct while the defect count is wrong. The physical meaning of the output to be measured should determine model selection.

Why is annotation engineering critical?

Annotation costs for a segmentation dataset may be higher than for drawing boxes. It is normal for two annotators to draw the true boundary of a fine crack differently. Annotation guidelines must define whether to include the defect's centerline or full width, a boundary that includes reflections or only the region distinct from the intact surface. If tolerances are not documented, the model's 'errors' may actually be annotation uncertainty.

Class colors in a pixel mask are only a visual aid; in the data format, every pixel must have a specific class ID. Resizing a PNG mask with interpolation may create intermediate values and corrupt class labels. Nearest-neighbor interpolation is generally preferred for masks; the interpolation used for the image may differ. This small implementation detail is the source of many training errors.

Real photograph of coins.
Real photograph / transformation: Real photograph of coins.

What does the U-Net architecture solve?

U-Net is known for its encoder-decoder structure and skip connections between different resolution levels. The encoder gathers context while reducing spatial dimensions; the decoder produces a denser pixel prediction. Skip connections can help transfer high-resolution local detail to the decoder. Although this architecture originated in medical imaging, it is also a useful starting point for controlled production images.

Using U-Net does not recover the exact boundary of every fine defect. If the image scale is inadequate and annotations are inconsistent, skip connections cannot create physical information. Memory consumption can also be high for very high-resolution images. Methods such as patch-based training, multiscale losses and boundary-aware evaluation may be considered. Their benefits must be demonstrated on real data.

Encoder-decoderResolution decreases as context increases, then is restoredencoderbottleneckdecodermaskConceptual technical diagram · Not an architectural drawing to scale
Original diagram: Resolution decreases as context increases, then is restored

Why are DeepLab and atrous convolution important?

The DeepLab family is known for designs that use dilated/atrous convolution to capture broader context without increasing sampling density. Multiscale context mechanisms such as atrous spatial pyramid pooling can help handle objects of different sizes. However, architectural details vary between DeepLab versions; any specific result must state which version and backbone were used.

Deep encoder features may carry strong semantic context but lose the sharp boundaries of a small defect. A decoder or dedicated boundary refinement components attempt to reduce this gap. For a fine crack, a rough weld seam or minor damage to cable insulation, preserving the pixel boundary is not a luxury but a task requirement.

Instance segmentation with Mask R-CNN

Mask R-CNN is a classic instance segmentation approach that adds a mask head to a Faster R-CNN-style object proposal structure. The model can associate a box and mask with each object instance. When multiple separate parts in a single image must both be located and have their shapes extracted, this architecture family provides an understandable baseline.

However, the model's mask may be calculated only within the proposed object region. If no proposal is found, the mask for that object is also likely to be missing. Annotation policy must also be clear for intersecting or overlapping parts. The two-stage structure of Mask R-CNN may not provide the most suitable latency on every hardware platform; testing on the actual target device is necessary.

Mask2Former and the mask classification approach

Mask2Former aims to unify semantic, instance and panoptic segmentation within a mask classification framework. Its masked-attention mechanism helps queries focus on relevant regions. Considering segment candidates rather than conventional dense pixel classification offers a strong alternative for some tasks. However, the model's effectiveness depends on the data, resolution, number of classes and training protocol.

Choosing Mask2Former for production cannot be justified simply because it is newer. On the same data split, it must demonstrate better boundary error, a lower miss rate or acceptable latency compared with a U-Net-based baseline. In many inspection applications, a simple, stable solution with low maintenance costs may be the better choice.

IoU, Dice and boundary metrics

Pixel IoU is the ratio of the intersection pixels of the predicted and reference masks to their union pixels. Dice similarity uses twice the overlap divided by the sum of the mask sizes. These metrics convey similar information, but require careful interpretation with class imbalance and small defects. A system that correctly predicts a large background may still miss a small critical defect.

Boundary quality becomes particularly important for thin objects. For example, shifting a two-pixel-wide crack mask sideways by one pixel may cause a substantial change in area. The same shift in the mask of a large part, by contrast, affects overall IoU very little. Boundary-focused measures such as Boundary IoU, boundary F-score or Hausdorff distance can be added as appropriate for the task.

Evaluating masksIoU, Dice and boundary quality are separate concernspredictiontruthoverlapboundaryConceptual technical diagram · Not an architectural drawing to scale
Original diagram: IoU, Dice and boundary quality are separate concerns

A pixel mask is not a physical measurement

A segmentation result covering 25,000 pixels has no meaningful value in mm² on its own. Scale, perspective, lens distortion and the working plane must be known. If the camera views the object at an angle, the physical size represented by one pixel may vary across the image. Converting a mask directly to surface area without calibration produces systematic errors in a precision quality inspection system.

For example, with a scale of 0.05 mm/pixel on a fixed plane, the area of one pixel is 0.0025 mm². An area of 25,000 pixels is approximately 62.5 mm². However, this calculation is correct only if the same scale applies along both axes and throughout the region. Measurement uncertainty, contour position and optical calibration must be evaluated separately.

Fine-defect boundaryAn error of a few pixels can affect the actual measurementpixelsboundaryerrormeasurementConceptual technical diagram · Not an architectural drawing to scale
Original diagram: An error of a few pixels can affect the actual measurement

Why do fine scratches require specialized design?

A scratch may be long but very narrow. The influence of the large number of background pixels in the image can dominate the classification loss; the model may incur a low penalty by always predicting background. Dice- or focal-type losses can help address class imbalance, but they do not fix incorrectly annotated or optically invisible scratches. High-resolution training and edge-aware evaluation are important for thin objects.

An application measuring scratch length may also require centerline/skeleton extraction. Skeletonization reduces the mask to a thin topological representation, but thickness variation, noise and disconnected segments affect the result. If nearby scratches merge, the skeleton takes on a different structure. Such a measurement must be validated using calibrated references and examples from the field.

Post-processing applied to masks

Operations such as morphological opening, closing, hole filling and removal of small connected components can make a mask look cleaner. However, removing small components may erase a critical fine defect. Filling a hole may conceal a real hole or void defect. 'Post-processing makes the mask look better' is not sufficient justification for quality inspection.

Post-processing thresholds should be justified in units such as mm² or physical length. A pixel-based threshold has a different physical meaning when camera resolution changes. Model output, post-processing and the decision threshold should be versioned separately; ablation studies should measure which component improves the error.

Post-processingRemoving small islands is not always correctmaskfiltercomponentsriskConceptual technical diagram · Not an architectural drawing to scale
Original diagram: Removing small islands is not always correct

How are quality decisions made from segmentation output?

Once a defect mask has been obtained, total area, largest defect area, length, width, defect count or distance to a specific critical region can be calculated. Quality decisions are often based on these features and production tolerances. For example, 'total scratch area must not exceed 5 mm²' and 'the length of any single scratch must not exceed 8 mm' are different rules. The same mask may yield different decisions under these two rules.

Human inspection can be defined as a separate decision state for low-confidence or borderline measurements. The system therefore does not have to be limited to generating automatic rejects. If the measurement is critical, verification using a second view from another camera, a second model or a physical measuring instrument may be considered.

Subgroups for error analysis

Rather than evaluating segmentation errors with a single global score, examine them by defect size, type, location and material properties. Defects near edges, low-contrast scratches, touching objects and highly reflective regions may form separate subsets. The same global Dice value can conceal different operational risks.

If there are very few defective images, a single test example has a large effect on the score. Confidence intervals should be reported, and annotations should be reassessed by experts when necessary. Whether a difference of a few pixels violates the physical tolerance should be decisive in the evaluation.

Mask demonstration based on conventional Otsu thresholding; not a deep learning prediction.
Real photograph / transformation: Mask demonstration based on conventional Otsu thresholding; not a deep learning prediction.

Application example: missing paint coverage

Suppose missing paint is being inspected in a specific region of a metal part. In well-lit, geometrically aligned images, two-class semantic segmentation can separate coated and uncoated areas. These are then converted to physical area. However, if the part orientation changes, geometric alignment may be required first; different metallic highlights may disrupt the color difference.

In this problem, classification alone says 'paint missing' but does not provide the area or location of the missing paint. Object detection provides an approximate location, but represents the irregular paint boundary with a box. Segmentation expresses the actual decision region more directly. However, the cost of drawing a mask for every image and the model's maintenance requirements must be considered.

Binary thresholded view of a real wall texture.
Real photograph / transformation: Binary thresholded view of a real wall texture.

Which approach suits which task?

Requirement Suitable starting point Additional validation
Defective/defect-free decision Classification May be sufficient if location is not needed
Marking the defect location Object detection Is the box boundary sufficient?
Measuring defect area Semantic segmentation Calibration, boundary uncertainty
Separating multiple objects of the same type Instance segmentation Merged/occluded objects
Objects and ground classes Panoptic segmentation Is the output complexity really necessary?
Task-appropriate outputA class for decisions, a box for location, a mask for areadecisionboxmaskmeasurementConceptual technical diagram · Not an architectural drawing to scale
Original diagram: A class for decisions, a box for location, a mask for area

How do we define annotation boundaries in segmentation?

In fine-scratch segmentation, two operators may draw different masks for the same image. One operator may mark only the scratch center, while another marks the scratch along with the surrounding discoloration. If the quality standard measures scratch length, it must be clear whether the mask's centerline or outer edge is the reference. Otherwise, even a highly capable model is forced to learn two different annotation approaches at once.

It is useful to compare borderline examples with experts. Magnification at a specified resolution, line thickness, zoom level and maximum boundary tolerance can be defined in the annotation tool. If a very small defect is only two pixels wide, 'pixel accuracy' may appear high while remaining physically inadequate. In such a case, changing the optical system may be more effective than spending more hours on annotation.

Defect annotations must be consistent with other tasks for the same product. If an image is both classified as 'defect-free' and contains a defect mask, there is a contradiction in data management. This may be an example in which the quality decision allows a certain defect tolerance; if so, the presence of a mask must not be equated with automatic rejection. The annotation dictionary should align with physical quality criteria.

Mask pixel resolution and loss calculation

The model often produces a feature map at lower resolution than the input. The final mask is enlarged from this map through interpolation or a decoder. If a defect only a few pixels wide disappears in the intermediate representation, the final mask's high resolution can be misleading. Resizing an image from 2048 pixels to 512 pixels reduces the linear scale by a factor of four. A defect originally 8 pixels wide becomes approximately 2 pixels wide.

BCE, Dice and focal-type losses can each emphasize different types of error. However, loss selection alone does not compensate for inadequate resolution. If a scratch thickness limit in production is 0.2 mm, examples both below and above this limit must be tested for correct masking. A loss sensitive to class imbalance may make small defects easier to learn, but false alarm risk must also be monitored.

The pixel classes that make up a mask in supervised training also matter. Labels such as 'background', 'part', 'defect' and 'shadow' are useful in some tasks, but many classes that are difficult to distinguish increase model complexity. Class definitions should be detailed enough to support the physical properties measured in the operation.

How should boundary metrics and physical tolerances be interpreted together?

A model's mask may achieve 95% IoU with the reference while the tip of a critical scratch is 10 pixels too short. If scratch length is used for an acceptance decision right at the limit, this error can cause a product to be accepted incorrectly. High global IoU therefore does not imply production suitability. Boundary error, endpoint error and physical length error should be measured separately.

At a pixel scale of 0.04 mm/pixel, a 10-pixel endpoint error corresponds to 0.4 mm. This conversion is meaningful only when geometric correction and the local scale are valid. If the camera is tilted, optical distortion has not been corrected or the object has height variations, using a single pixel scale may be incorrect. Calibration uncertainty and segmentation uncertainty must be evaluated together.

An uncertainty band may be considered for borderline measurements in production. For example, if the tolerance is 5 mm and model and calibration uncertainty is ±0.3 mm, an output of 4.9 mm may not be sufficient for definitive automatic acceptance. The decision policy can route the uncertain range to manual inspection or a second method.

Instance segmentation and object-count consistency

When two parts touch, semantic segmentation may produce a single merged region. Connected-component analysis cannot split this merged region into two. Instance segmentation aims to represent every physical object with a separate mask. However, if object boundaries are visually ambiguous, separate model masks are not guaranteed either. Partial occlusion from a single camera viewpoint may not reveal the number of independent physical objects.

In instance-level evaluation, it matters which real object each mask matches. If one large mask covers two reference objects, pixel coverage may look high while the object count is wrong. Instance AP or object matching can therefore be reported together with product-level counting error. This distinction is particularly critical in robotic applications.

For panoptic segmentation, the distinction between 'which pixels belong to a ground class and which belong to countable objects?' must also be defined in advance. If assembly inspection requires only counting parts, a simpler instance approach may be sufficient. Learning the semantics of the entire scene sometimes creates unnecessary costs.

When does a two-stage quality system make sense?

On a high-speed line, a lightweight classifier may first select suspicious parts, with an expensive segmentation model applied only to those parts. This design can reduce the overall average inference cost. However, defects missed in the first stage never reach the second stage. Overall system recall therefore cannot exceed the recall of the first stage. The speed gain must be measured together with its reliability cost.

Another option is to apply segmentation to every product but perform a second verification only for borderline measurements. This approach does not skip critical defects in the first stage; the second stage focuses on uncertainty. The appropriate design depends on processing time per product, actuator distance and the cost of missed defects.

System outputs must be reproducible. Storing the mask model version, post-processing parameters, calibration file and acceptance rules together makes it possible to identify which change affected a result during an error investigation. Saving only the PNG mask is often insufficient for tracing a physical quality decision.

Advanced engineering details to consider in deployment

Is a mask enough to measure defect area?

A pixel mask gives the defect's area in the image plane, not automatically its real-world area. Perspective can cause pixel scale to vary across the image. If the surface is not planar, homography-based correction may also be inadequate. For a fine scratch, a mask that is four pixels wide rather than two can double the calculated area. Calibration, edge uncertainty and acceptance tolerance must therefore be evaluated together in mask-based measurement. Optimizing a segmentation model for a high Dice score does not necessarily reduce error in millimeters by the same proportion.

The boundary between semantic and instance segmentation

Two overlapping identical parts may have the same pixel classes. Semantic segmentation does not have to distinguish which object instance these pixels belong to; instance segmentation produces separate masks for different objects. However, boundaries may be uncertain where two objects physically touch. Panoptic segmentation is a broader representation combining 'thing' and 'stuff' categories; it may not be needed for every production problem. The output type should be determined by whether product count, individual object identity or surface area matters in the task definition.

Human uncertainty at annotation boundaries

The exact boundary of a paint defect is often not optically clear. Two experts may draw different masks for the same blemish. Treating the model as definitively correct against one mask and wrong against the other conceals the actual uncertainty in deployment. Multiple annotators, a consensus rule or an ignored uncertainty band can be used for critical boundary regions. However, the uncertainty band must not be used to exclude critical defects from evaluation. The higher the annotation quality, the more meaningful the engineering time spent optimizing the mask becomes.

Choosing resolution for fine lines

In segmentation architectures, encoder layers gain broader context while reducing detail. Skip connections and high-resolution features can help preserve thin structures. Nevertheless, a one-pixel line in the input image has weak physical reliability. Lighting changes, sensor noise and compression can make the line disappear. The solution starts with the right optics, enough pixels, consistent lighting and an appropriate mask. For scratches, geometric measurements such as length and direction, rather than just a segmentation mask, may also represent the operational decision more accurately.

Application scenario: rejection based on defect area

Suppose a defect area exceeding 1 mm² on a cast surface is a rejection criterion. The segmentation model masks the defect, but converting pixel area to physical area requires geometric scale and surface position. At the boundary of a fine defect, a three-pixel difference may change whether this threshold is exceeded. The experiment should therefore report both the mask's Dice score and physical area error. The acceptance threshold must be tied to production tolerance, not merely to producing visually attractive masks.

Field-test checklist

  • Is it documented which tests were kept independent by product, shift and imaging conditions?
  • Have failures that can be corrected by the algorithm alone been distinguished from those requiring optical or process changes?
  • Has it been verified that the model score does not replace the physical acceptance criterion?
  • Are input resolution, model version, threshold and operating hardware held constant in the experiment records?
  • Are illustrative visuals clearly distinguished from actual measured model results?
  • Are false rejects, missed defects, latency and reinspection workload reported separately?

Frequently asked questions

What is the difference between segmentation and detection?

Detection generally produces boxes with class labels, while segmentation produces pixel-level masks. If precise area or boundaries are required, a mask may be more appropriate; if only approximate location is needed, a box is a less costly solution.

Should U-Net be avoided because it is an older model?

No. U-Net and its variants can be strong baselines when the task and data are suitable. The age of a model family alone is not an indicator of technical quality.

If Dice is high, is the measurement accurate?

No. Even with high mask overlap, an error of a few pixels at a critical boundary may exceed the physical tolerance. Calibration and measurement uncertainty must be calculated separately.

Which loss function should be chosen for fine scratches?

Losses sensitive to class imbalance can be tried, but the visual quality of the data, resolution and annotation standard are often more decisive. The choice should be made experimentally.

Is it safe to remove small components to clean up a mask?

Only if the regions to be removed have been verified to be physically insignificant. This operation can also erase real small defects.

References and image provenance

Technical references and original publications are listed below. The photographs used in the visual examples are genuine CC0/public-domain images; transformations made for comparison are explained. The diagrams are original designs. Illustrative examples are not presented as trained-model performance.

  1. https://arxiv.org/abs/1505.04597
  2. https://arxiv.org/abs/1703.06870
  3. https://arxiv.org/abs/2112.01527
  4. scikit-image example data: source photographs and reuse notes

Image sources and illustration note

The photographic examples are taken from the scikit-image sample data collection. Added boxes, masks, synthetic defects and heatmaps are demonstrations that explain concepts; they are not outputs of a trained model or validated performance results. The technical diagrams are original drawings included in the package.

Source and usage notes for sample images