Skip to Content
ElectronicsElectronics
  • Article
  • Open Access

11 February 2026

24 Pages

CD-Mosaic: A Context-Aware and Domain-Consistent Data Augmentation Method for PCB Micro-Defect Detection

,
,
,
and
State Key Laboratory of Extreme Environment Optoelectronic Dynamic Measurement Technology and Instrument, North University of China, Taiyuan 030051, China
*
Author to whom correspondence should be addressed.

Abstract

Detecting minute defects, such as spurs on the surface of a Printed Circuit Board (PCB), is extremely challenging due to their small size (average size < 20 pixels), sparse features, and high dependence on circuit topology context. The original Mosaic data augmentation method faces significant challenges with semantic adaptability when dealing with such tasks. Its unrestricted random cropping mechanism easily disrupts the topological structure of minute defects attached to the circuits, leading to the loss of key features. Moreover, a splicing strategy without domain constraints struggles to simulate real texture interference in industrial settings, making it difficult for the model to adapt to the complex and variable industrial inspection environment. To address these issues, this paper proposes a Context-aware and Domain-consistent Mosaic (CD-Mosaic) augmentation algorithm. This algorithm abandons pure randomness and constructs an adaptive augmentation framework that synergizes feature fidelity, geometric generalization, and texture perturbation. Geometrically, an intelligent sampling and dynamic integrity verification mechanism, driven by “utilization-centrality”, is designed to establish a controlled sample quality distribution. This prioritizes the preservation of the topological semantics of dominant samples to guide feature convergence. Meanwhile, an appropriate number of edge-truncated samples are strategically retained as geometric hard examples to enhance the model’s robustness against local occlusion. For texture, a dual-granularity visual perturbation strategy is proposed. Using a homologous texture library, a hard mask is generated in the background area to simulate foreign object interference, and a local transparency soft mask is applied in the defect area to simulate low signal-to-noise ratio imaging. This strategy synthesizes visual hard examples while maintaining photometric consistency. Experiments on an industrial-grade PCB dataset containing 2331 images demonstrate that the YOLOv11m model equipped with CD-Mosaic achieves a significant performance improvement. Compared with the native Mosaic baseline, the core metrics mAP@0.5 and Recall reach 0.923 and 86.1%, respectively, with a net increase of 8.3% and 8.8%; mAP@0.5:0.95 and APsmall, which characterize high-precision localization and small target detection capabilities, are improved to 0.529 (+3.0%) and 0.534 (+3.3%), respectively; the comprehensive metric F1-score jumps to 0.903 (+6.2%). The experiments prove that this method effectively solves the problem of missed detections of industrial minute defects by balancing sample quality and detection difficulty. Moreover, the inference speed of 84.9 FPS fully meets the requirements of industrial real-time detection.

1. Introduction

Printed Circuit Board (PCB), as the core carrier in the electronics industry, its manufacturing quality directly determines the reliability and performance of modern electronic devices. With the development of electronic components toward miniaturization and high density, the line width of PCBs has been reduced to the micron level, resulting in extremely concealed defects such as burrs and microcracks [1,2]. Although the pixel density of such defects is extremely low, they can easily cause short circuits or signal integrity problems and are key contributors to functional failures [3]. Traditional automated optical inspection (AOI) systems rely on manually designed features and thresholds. When facing complex and variable background textures (such as differences in gold immersion and tin spraying processes), they often exhibit high false alarm rates and low generalization ability [4,5].
In recent years, deep learning methods based on convolutional neural networks (CNNs) have gradually become the mainstream solution for industrial defect detection due to their powerful feature-extraction capabilities [6]. The YOLO (You Only Look Once) series of algorithms [7,8,9] is widely used in industrial online detection thanks to their excellent balance between real-time performance and accuracy. Although the latest YOLOv11 has further improved general detection performance through programmable gradient information and end-to-end strategies [10], it still faces enormous challenges in handling extremely tiny and sparse features. For PCB scenarios, Tang et al. [11] proposed PCB-YOLO, which enhances global perception capability by introducing the Swin Transformer, while Xiao et al. [12] designed CDI-YOLO, which optimizes lightweight deployment by incorporating the coordinate attention mechanism. In fact, the recognition of tiny defects in such complex backgrounds is not a unique challenge exclusive to the PCB field, but rather a common problem prevalent across the broader domain of industrial precision manufacturing inspection. For instance, in the non-destructive testing (NDT) of steel-structure welds, the semi-supervised Generative Adversarial Network (SGT-Net) recently proposed by Luo et al. [13] effectively addresses similar predicaments of high-noise interference and an extreme scarcity of annotated samples through transfer learning and the exploitation of unlabeled data. These successful cross-domain practices have revealed a widespread consensus in the field of industrial vision: addressing feature sparsity and data imbalance is the key to achieving highly robust detection. Nevertheless, regardless of the improvements made to algorithm architectures, training high-performance models always relies on massive volumes of high-quality annotated data [14]. In actual industrial production, the acquisition cost of defect samples (especially tiny defects) is extremely high, and their distribution is highly unbalanced, posing typical challenges of few-shot learning and long-tail distribution [15,16].
To alleviate the problem of data scarcity, data augmentation has emerged as a low-cost and highly efficient solution. In the general object detection scenario, Mosaic augmentation [17] constructs local views by randomly stitching four images and applying random cropping, which significantly enhances generalization to occluded scenarios. However, when Mosaic is directly applied to the PCB micro-defect detection task, its core mechanism based on “randomness” faces semantic challenges specific to this domain. The root cause is that PCB defects (such as a spur) have a strong topological context dependence. Unlike macroscopic objects with feature redundancy in natural images, spur defects are extremely small in scale (average size < 20 pixels) and must be attached to conductive traces [18]. The blind random cropping strategy of the original Mosaic is prone to cutting off the crucial physical connection between the defect and the circuit, causing the defect to degrade into isolated noise points lacking circuit logic support. This loss of semantic context not only fails to bring the expected generalization gain but also introduces harmful label noise [19].
Secondly, the general pixel-level enhancement strategy has serious feature adaptability issues in the imaging of tiny PCB defects. The linear interpolation strategy adopted by global mixing methods (e.g., Mixup [20]) can easily cause the features of tiny defects with weak signals to be completely submerged by complex background textures, leading to a significant decrease in the signal-to-noise ratio [21]. In contrast, the solid-color black blocks introduced by regional occlusion methods (e.g., Cutout [22]) create non-natural strong-gradient edge artifacts. This artificially synthesized noise disrupts the photometric consistency of the image and can easily lead the model to overfit toocclusion boundaries rather than to real industrial defect patterns. Although the subsequent GridMask [23] attempts to strike a balance between information preservation and occlusion by introducing a structured grid strategy, its regular grid lines that cover the entire image forcibly sever the originally connected circuit topology. These high-frequency artificial edges are highly susceptible to being misinterpreted by the model as circuit fractures or structural abnormalities. Such artificially synthesized noise severely undermines the photometric and geometric consistency of the image, and tends to cause the model to overfit to occlusion boundaries rather than the actual morphology of industrial defects [24].
In response to the particularities of PCB micro-target detection, recent studies have been dedicated to exploring enhancement paradigms with better “context awareness” and “domain consistency”. Although Ghiasi et al. [25] proposed the Copy-Paste strategy to effectively increase the density of small targets, this method pastes defects into non-conductive areas, ignoring the rationality of background semantics and disrupting the data distribution law. Gordienko et al. [26] attempted to retain contextual information through feature-level enhancement, but its complex calculation process incurs significant training overhead. In the field of industrial vision, Wang et al. [27] further pointed out that designing enhancement strategies in line with the imaging mechanism for specific manufacturing scenarios (such as uneven illumination and foreign object interference) is more crucial than blind data augmentation. However, there is still a lack of an end-to-end enhancement framework that can jointly consider “topological integrity protection” and “visual hard examples synthesis”.
To address the limitations of the aforementioned native augmentation strategies for detecting tiny PCB defects, this paper proposes a Context-aware and Domain-consistent Mosaic (CD-Mosaic) augmentation algorithm. Abandoning blind randomness, the proposed method constructs a synergistic data augmentation framework that integrates geometric constraints and texture perturbation. At the geometric level, we establish an intelligent sampling and topological integrity verification mechanism driven by “utilization-centrality”, which aims to construct a controlled sample-quality distribution to balance feature fidelity and geometric generalization. At the texture level, we design a dual-granularity visual perturbation strategy that leverages a homologous texture library to generate hard masks and soft masks. This approach effectively synthesizes hard visual cases without disrupting the data distribution, compelling the model to focus on more robust fine-grained features. To sum up, the core contributions of this paper are as follows:
  • Unlike the standard Mosaic augmentation, which lacks topological constraints and tends to destroy the circuit context of tiny defects, we propose a geometric optimization module integrated with intelligent sampling and dynamic integrity verification. This mechanism transforms the cropping strategy from blind randomness to a controlled distribution, which effectively suppresses invalid samples while strategically retaining an appropriate number of geometric hard cases to ensure the generalization performance of the model.
  • Addressing the generic masking techniques that are prone to introducing artificial artifacts and disrupting data distribution, we design a dual-granularity visual perturbation module based on homologous textures. Under the premise of strictly maintaining photometric consistency, this strategy physically simulates foreign object occlusion and low signal-to-noise ratio (SNR) imaging scenarios, thereby significantly enhancing the model’s anti-interference capability and feature extraction ability in complex industrial backgrounds.
  • Experiments on an industrial-grade PCB dataset containing 2331 images verify the superiority of the proposed method. The YOLOv11m model equipped with CD-Mosaic achieves an mAP@0.5 of 0.923 (+8.3%), an mAP@0.5:0.95 of 0.529 (+3.0%), an APsmall of 0.534 (+3.3%), a precision of 95.0% (+2.7%), a recall of 86.1% (+8.8%), and an F1-score of 0.903 (+6.2%). Moreover, the inference speed of 84.9 FPS fully meets the requirements for real-time industrial detection, which validates the practical value of the proposed method in addressing the long-tail distribution and high miss-detection rate issues of small industrial targets.

2. Methods

2.1. Overall Architecture of CD-Mosaic

As shown in Figure 1, the CD-Mosaic algorithm establishes an adaptive augmentation framework that integrates intelligent hierarchical sampling, topological integrity verification, and dual-granularity visual perturbation. This framework aims to transform original PCB images into high-quality training samples possessing both geometric diversity and texture robustness. The framework consists of the following three core stages:
Figure 1. Overall flowchart of the CD-Mosaic algorithm.
Utilization and centrality-driven intelligent sampling: In this stage, dual indicators of the training counter and defect centrality are introduced. By preferentially selecting low-frequency samples and implementing a hierarchical hybrid strategy of “3 high-centrality samples + 1 random sample”, a candidate pool for splicing with both feature quality and balanced distribution is constructed at the source.
Topological integrity stitching based on protection domains: Topological protection boxes encapsulating circuit semantics are constructed, and an integrity verification mechanism is embedded into the geometric transformations. By strictly preserving the complete topological structure of dominant samples (≥70%) while allowing moderate edge truncation, a dynamic balance between feature fidelity and geometric generalization is achieved. This design concept aligns with the view emphasized in recent studies on maintaining feature topological consistency in small object detection [28,29].
Dual-granularity visual perturbation enhancement: Based on the principle of homologous texture consistency, “hard masks” and “transparent soft masks” are applied to the background area and the defect area, respectively. This strategy simulates foreign object occlusion and low signal-to-noise ratio imaging, achieving the synthesis of hard examples at the visual level while maintaining consistency in the data domain distribution.

2.2. Phase One: Context-Aware Intelligent Splicing

The original Mosaic algorithm relies on random cropping centers (xc, yc) to perform spatial transformations. Its success in general scenarios, such as COCO [30], can be attributed to the feature redundancy of generic objects, meaning that local truncation usually does not compromise semantic recognizability. However, this assumption fails in the detection of tiny PCB defects. As Hua et al. [31] pointed out, tiny targets are extremely sensitive to geometric truncation. For spur defects with an average scale of only about 20 pixels, random cropping can easily sever the conductive traces they adhere to, causing the samples to lose topological context and degrade into invalid noise. However, this does not mean that geometric truncation should be completely abandoned, as moderate perturbations are crucial for preventing the model from overfitting to canonical samples and enhancing its robustness against interference. Therefore, instead of relying on blind random probabilities, this paper introduces a prior-guided mechanism and proposes an improved splicing strategy that includes intelligent sampling and topological integrity verification. By actively intervening in the cropping distribution, this strategy aims to construct a controlled sample-quality distribution in which core-topology integrity coexists with moderate edge truncation, thereby achieving a dynamic balance between ensuring the model learns the real defect morphology and enhancing its robustness in complex scenarios.

2.2.1. Balanced Sampling Strategy Based on Geometric Prior

Although the cropping center in Mosaic follows a uniform distribution on the two-dimensional plane, as analyzed from the perspective of geometric probability, the expected retention of targets at different positions exhibits a significant center bias. Specifically, the region located at the geometric center of a sub-image has the highest probability of being completely included in the final view, whereas edge regions face extremely high truncation risks. Given the strong dependence of tiny defects on topological integrity, we leverage this geometric property to propose an intelligent sampling strategy combining “defect centrality” and “sample utilization”. This strategy aims to actively guide sparse defect features into a geometric safety zone with high expected retention.
To quantify the topological robustness of samples under random spatial transformations, we define the scale-normalized geometric safety zone ΩC. Based on the statistical analysis of the spatial distribution of defects in the training set, we set the safety margin against random perturbations to μ (i.e., the region where the image boundary contracts 15% inwards). Then, the geometric safety zone ΩC is defined as the interval [0.15S, 0.85S], where S is the size of the input image. The selection of this interval is based on an empirically constructed geometric balance. The central safe area accounts for approximately 50% of the total image area (0.7 × 0.7 = 0.49), which balances the probability of defects being identified as high-centrality anchors and edge-distributed hard examples. For any image Ii, its centrality score Cscore(Ii) is defined as follows:
C s c o r e ( I i ) = ∑ j = 1 N i I ( ( x j , y j ) ∈ Ω C )
where Ni represents the total number of defects in the image Ii, and (xj, yj) is the scaled center coordinates of the j-th defect. I ( · ) is an indicator function, which takes the value of 1 if and only if the defect center falls within the geometric safety zone ΩC, and 0 otherwise. This scoring mechanism mathematically selects the “robust samples” with the highest expected survival for subsequent stitching, providing a stable feature flow for training.
To maximize sample quality while avoiding overfitting on simple samples and to address the issue of unbalanced sample utilization in industrial datasets, we propose a “utilization-centrality” driven hierarchical sampling strategy. This strategy maintains a global counter Cuse to record the sampling frequency of each image in the current training epoch in real-time. When constructing each 2 × 2 mosaic image, the following three steps are performed:
Fairness screening: First, construct a candidate pool Pcand. Prioritize the selection of images with the smallest global counter Cuse, which are the long-tail samples with the lowest utilization rate in the current training, to ensure that all defects have an equal chance of gradient update.
Quality stratification: In Pcand, the samples are sorted in descending order according to the aforementioned Cscore and then divided into “high centrality samples” and “low centrality samples”.
Stratified random sampling: To balance the learning of dominant features and anti- interference ability of the model, we adopt a 70/30 hybrid strategy to select the final four subgraphs. Specifically, the algorithm first randomly selects three subgraphs from the high-centrality samples as dominant signals. This ensures that defects are located within the geometric safety zone, preserving the complete topological structure and guiding the model to converge rapidly and learn the core defect morphology. Meanwhile, one subgraph is randomly selected from the remaining samples as a perturbation signal. By introducing an appropriate number of edge samples to generate geometric hard examples, it mimics the non-ideal field-of-view distribution in industrial settings, preventing the model from overfitting to the central position and enhancing its inference robustness for truncated features.

2.2.2. Mosaic Stitching with Dynamic Quality Constraints

Although intelligent sampling in the previous stage optimized the quality of the candidate sample pool, the inherent random cropping mechanism of Mosaic may still introduce uncontrollable positional biases. To prevent the loss of key information of tiny defects due to excessive truncation during geometric transformation, this paper proposes a dynamic integrity verification mechanism based on context protection boxes. The core of this mechanism lies in finding the best balance between feature fidelity and geometric generalization by introducing controllable geometric constraints.
Specifically, given that the identification of spur defects is highly dependent on their connectivity to conductive traces, a simple defect bounding box is insufficient to capture this crucial topological information. Therefore, we construct a context protection box (Bctx), which is defined as an area obtained by expanding the margin m outward from the original annotation box (Bctx = Bgt + m). Based on the dataset statistics reported in Section 3.1, under an input resolution of 640 × 640, the mean size of spur defects is approximately 20 pixels; accordingly, we set m to 20 pixels, matching the defects’ average scale. This configuration effectively extends a buffer region around each defect equal to its own size, ensuring that the crop window fully encloses the defect entity and its neighboring circuit topology, thereby forming a minimal unit that preserves complete physical semantics.
On this basis, we embedded a trial-and-error integrity verification loop in the coordinate mapping process. During each generation of training samples, the algorithm first performs the standard Mosaic geometric transformation. Based on the randomly generated cropping center (xc,yc), it stitches four subgraphs together and performs window cropping to generate a candidate enhanced view. Subsequently, we immediately conduct a posterior verification on this view and calculate the ratio Rintegrity of the number of intact context protection boxes in the current view to the total number of defects in the original four subgraphs:
R i n t e g r i t y = ∑ k = 1 N t o t a l I ( B c t x ( k ) ⊂ V c r o p ) N t o t a l
where Ntotal represents the total number of defects in the stitched image; Vcrop denotes the currently randomly generated cropping window; and I ( · ) is the indicator function (which takes the value of 1 only when the context bounding box B c t x ( k ) is completely contained within the cropping window; otherwise, it takes the value of 0). If Rintegrity ≥ τ, the candidate view is deemed valid and retained. Conversely, if Rintegrity < τ, it indicates that the random cropping has removed too many critical features; the algorithm discards the candidate view and triggers the resampling mechanism to generate a new crop center (xc,yc) for the next attempt, repeating until the constraint is satisfied or the maximum number of attempts Tmax is reached. If the timeout occurs, a center crop is enforced to ensure training stability. The threshold τ is a key hyperparameter controlling model behavior: An excessively low τ causes severe information loss, leading to underfitting, whereas an excessively high τ suppresses the generation of truncated samples and reduces the model’s generalization ability on boundary targets, resulting in overfitting. To determine the optimal balance point, we conducted a sensitivity analysis of τ without employing the mask augmentation strategy described in Section 2.3. We evaluated τ ∈ {0.6, 0.7, 0.8, 0.9, 1.0} in comparative experiments; the results are shown in Table 1.
Table 1. Sensitivity analysis results of the topological integrity threshold τ.
The experimental results exhibit an inverted U-shaped distribution. The model achieved optimal performance at τ = 0.7 (mAP@0.5 = 0.885). This outcome intuitively reflects the dual impact of τ on model performance: when τ is set too low (e.g., 0.6), excessive stochastic truncation destroys the already sparse topological features of small defects, resulting in insufficient feature fidelity; conversely, when τ is set too high (e.g., 1.0), edge-truncation samples are completely excluded from the training set, leaving the model unexposed to geometric hard cases caused by local occlusions and thereby limiting its geometric generalization capability. Therefore, τ = 0.7 effectively balances the two considerations: it ensures that, within a single training sample, at least 70% of defects retain their complete topology, allowing the model to observe defects’ true morphology, while permitting up to 30% of defects to be randomly truncated, forcing the model to attempt inference under incomplete information and thereby improving its robustness to occlusion scenarios. Based on this analysis, we fix τ = 0.7 in subsequent experiments.
As shown in Figure 2, compared with native Mosaic (Figure 2a), which suffers severe information loss due to indiscriminate cropping and leaves only four valid targets within the window, the CD-Mosaic constrained by τ = 0.7 (Figure 2b) preserves eleven samples under the same input scale and establishes a distributional paradigm of “predominantly intact samples (81.8%) + coexisting truncated samples (18.2%)”. The predominance of intact samples ensures the model’s accurate learning of core topological features, while the strategically retained small number of edge-truncated samples effectively simulates local occlusion scenarios and provides a high-quality geometric basis for the subsequent introduction of texture perturbations.
Figure 2. Schematic diagram of the comparison between the native Mosaic random cropping and the protection mechanism proposed in this paper.

2.3. Phase Two: Dual-Granularity Visual Perturbation for Domain Consistency

Although Phase I effectively reduces the geometric truncation risk of minor defects, the stitched samples still lack complex interference from industrial sites in the texture dimension. The general augmentation strategies face an adaptability bottleneck here. The non-natural black blocks introduced by Cutout disrupt the domain consistency of the images, and the global mixing in Mixup tends to submerge sparse high-frequency defect features in the background. Therefore, this section proposes a differential augmentation strategy based on homologous textures, aiming to implement dual-granularity visual Perturbation in parallel with the imaging mechanism within the same training sample. This strategy adopts a differential “mask injection” paradigm, and by applying controlled homologous texture masks to the background and defect areas, respectively, it achieves the synthesis of hard examples at the visual level while maintaining the consistency of the photometric distribution.

2.3.1. Homologous Texture Sampling

To ensure the texture authenticity of the mask, we abandon artificially synthesized noise and adopt instant homologous sampling instead. For the currently input stitched image Imosaic, the area without the gray border is defined as Maskvalid, and the union area of all defect context protection boxes is defined as ∪(Bctx). The texture block acquisition function Fpatch(w,h) is defined as follows: Randomly extract an image block P of size w × h from the safe background region Ωsafe = Maskvalid − ∪(Bctx), which ensures that the noise distribution, lighting conditions, and resolution of the mask are completely consistent with those of the background. As emphasized by Yu et al. [32], inconsistent illumination ratios and noise distributions can significantly interfere with feature extraction. Therefore, this strategy eliminates the “domain shift” introduced by data augmentation through strict photometric consistency constraints, forcing the model to learn the texture structure itself rather than the photometric differences.

2.3.2. Strategy A: Hard Mask in the Background Area (Simulating Foreign Objects)

For non-defective background regions, this strategy aims to simulate the occlusion of foreign objects such as common dust, solder balls, or residual glue stains in the production environment. The algorithm randomly generates Nhard interference blocks (Nhard ∈ [5, 8]) in each training image and performs mask injection based on the principles of feature adaptability and spatial mutual exclusion.
Specifically, although real industrial foreign objects exhibit irregular shapes, this study approximates them using rectangular masks. This design choice is not merely a geometric simplification of an irregular object’s bounding box; its fundamental rationale lies in the feature-extraction mechanism of convolutional neural networks. Because the convolutional kernel itself has a rectangular distribution, the rectangular high-frequency edges introduced by a hard mask are sufficient to induce pronounced gradient discontinuities in deep feature maps [33,34]. From a receptive-field perspective, these abrupt, hard edges sever local spatial correlations in background textures, creating strong distractors that the feature extractor struggles to accommodate. As DeVries et al. [22] demonstrated in their Cutout study, such non-target strong-gradient signals generate substantial penalty terms during backpropagation, forcing convolutional kernels to adjust their weight distributions and to actively learn to suppress these anomalous high-frequency background activations. Consequently, the network’s robustness in complex industrial environments is significantly enhanced and its false-alarm rate reduced.
In the specific implementation of mask generation, to simulate the diversity of foreign object scales, we jointly randomize the aspect ratio r ∈ [0.5, 2.0] and the area ratio A~U (0.5%, 2.0%) to dynamically determine the mask size (Wm,Hm):
W m = A ⋅ S i m g ⋅ r , H m = A ⋅ S i m g r
Here, Simg represents the total pixel area of the input image. This parameter range is sufficient to cover the spatial characteristics of various foreign objects, ranging from elongated shapes (e.g., glue stains) to blocky shapes (e.g., solder balls). Subsequently, to prevent the enhancement operation from accidentally occluding real defects and introducing “label noise,” the algorithm imposes strict spatial mutual-exclusion constraints. For the randomly generated mask position Bh, the intersection over union (IoU) between it and all real defect annotation boxes Bgt in the image is calculated. The algorithm only retains the masks that satisfy m a x ( I o U ( B h , B g t ) ) = 0 and performs opaque pasting using the homologous texture block Phard obtained in Section 2.3.1:
I ( x , y ) = P hard ( x , y ) , ∀ ( x , y ) ∈ B h
This strategy significantly increases the semantic complexity of the background by introducing homogeneous, high-frequency texture interference in the secure area, forcing the model to develop more robust background-suppression capabilities.

2.3.3. Strategy B: Soft Mask in Defective Regions (Generation of Hard Examples for Tiny Targets)

Given that micro-defects have extremely few pixels and their semantics are prone to being lost due to direct occlusion, this section proposes a soft-masking strategy based on local transparency blending, aiming to simulate implicit degradation scenarios such as uneven solder mask, out-of-focus imaging, or low contrast. Unlike the physical occlusion of hard masks, this strategy reduces the saliency of defects while preserving their topological structures by overlaying partially transparent homologous textures. To balance feature learning and hard-example synthesis and prevent model divergence caused by excessive enhancement, the algorithm introduces a probability-trigger mechanism, which randomly activates this process with a probability of p = 0.3 to construct a training distribution where clear samples dominate and fuzzy hard examples coexist.
Specifically, the algorithm first performs dynamic scale matching and random perturbation of the center coordinates. Based on the original defect size (Wd, Hd) and the geometric center (xc, yc), a random scaling factor λ ~ U(0.5, 1.5) is introduced to determine the mask size, and a random position offset is applied to the original center to obtain a new mask coverage box Bs. This dual random perturbation of scale and position builds diverse occlusion scenarios. When λ < 1.0, partial occlusion of the defect can be achieved; when λ > 1.0, mixed coverage of the defect and the surrounding background is realized, effectively preventing the model from overfitting to specific noise patterns. Subsequently, a homologous texture block Ptex that exactly matches the size of Bs is cropped from the safe background Ωsafe, and the current mask area Iregion’s image pixels are weighted and synthesized using a random transparency coefficient α ∈ [0.2, 0.5].
I r e g i o n ′ = α ⋅ P t e x + ( 1 − α ) ⋅ I r e g i o n
Finally, a pixel-level synthesis operation is performed to precisely embed the generated low signal-to-noise ratio view Iregion into the corresponding coordinates of the original image. Unlike the hard-mask strategy used in Section 2.3.2 for background foreign objects (which aims to suppress negative samples via strong gradients), for minute defect regions, we must prioritize preserving gradient continuity. For defects that occupy very few pixels, hard occlusion can lead to the complete loss of critical topological information (i.e., gradient vanishing), rendering the model incapable of learning from such samples. In contrast, the soft-mask strategy based on transparency mixing constructs adversarial perturbations in feature space. Drawing on the adversarial training theory of Goodfellow et al. [35], this operation preserves topological structure while reducing the signal-to-noise ratio, thereby forcing convolutional kernels to refrain from relying on simple strong-edge features and instead to optimize perceptual weights sensitive to subtle textural differences. The essence of this strategy is feature suppression rather than removal: it does not destroy defect topology but reduces defect saliency by superimposing homologous noise, compelling the model to learn to capture subtle edge gradients under low signal-to-noise conditions and thereby synthesize visually challenging examples.
Figure 3 intuitively demonstrates the differential effects of dual-granularity visual perturbations. In Figure 3a, the green solid boxes identify the intact original defects, while the red solid boxes indicate truncated defects. Additionally, the blue dashed boxes represent the topological protection boxes, and the blue solid lines mark the centerlines of the Mosaic stitching. In contrast to the hard mask (shown in Figure 3b, where purple solid boxes indicate opaque foreign object occlusion) that simulates "strong gradient" interference in the background area, the soft mask applied to the defect regions (depicted in Figure 3c by yellow dashed boxes) exhibits distinct semi-transparent characteristics. It can be observed that the enhanced minor defects are not fully covered; their topological attachment to the circuit remains faintly visible, yet the texture contrast is significantly reduced. This combination of strong background interference and soft blurring of defects closely replicates real-world industrial imaging conditions—characterized by uneven illumination and mixed foreign objects—thereby effectively improving the model’s robustness in non-ideal detection environments.
Figure 3. Schematic diagram of the enhancement effect of double masking.
To provide a comprehensive overview of the proposed framework, Algorithm 1 summarizes the complete execution process of CD-Mosaic. This algorithm integrates context-aware intelligent splicing (Section 2.2) and domain-consistent dual-granularity visual perturbation (Section 2.3) into a unified process.
Algorithm 1. Context-aware and Domain-consistent CD-Mosaic Enhancement Algorithm
Input: Original dataset D(Images I, Labels L); image size S; Usage counter Cuse;
Protection margin m = 20 px; Integrity threshold τ = 0.7;
Number of hard masks Nhard ∈ [5, 8]; Soft mask probability p = 0.3.
Output: Augmented image Iaug; Augmented labels Laug
1. Initialization and Smart Sampling
Calculate centrality score Cscore for each image//Count defects in geometric safety zone [0.15S, 0.85S]
Sort dataset D in ascending order based on Cuse//Prioritize Low-frequency samples
Ibatch ← Select 3 images with highest Cscore + 1 random image from the rest
Update Cuse for the selected images
2. Topology-Aware Mosaic
Repeat
   Define protection box Bctx ← Bgt ± m//Expand m pixels to include circuit context
   (xc,yc) ← Generate random mosaic center in range [0.5S, 1.5S]
   Imos,Lmos,Maskvalid ← NativeMosaic(Ibatch,xc,yc)//Maskvalid excludes gray borders
   Calculate Integrity Rate R ← (Count of complete Bctx)/(Total defects)
Until R ≥ τ or Max Attempts reached//Ensure ≥ 70% topological completeness
3. Dual-Granularity Visual Perturbation
Define safe region Ωsafe ← Maskvalid\(∪Bctx)//Exclude gray borders and all defect contexts
/* Strategy A: Hard Mask (Foreign Object Simulation) */
For k = 1 to Rand(Nhard)do
   Generate random block Bh (Area ∈ [0.5%, 2.0%]S2, Aspect ratio ∈ [0.5, 2.0])
   If Bh is strictly inside Ωsafe then
       Phard ← Crop homologous texture patch randomly from Ωsafe
       Imos ← Paste Phard into Bh location
   End if
End for
/* Strategy B: Soft Mask (Low SNR Simulation) */
For each defect d in Lmos do
   If Rand(0,1) < p then
       Generate jittered box Bs (Scale λ ~ U(0.5, 1.5) based on Bctx, random shift)
       Ptex ← Crop texture patch of size strictly equal to Bs from Ωsafe
       α ← Rand(0.2, 0.5)
       Iregion ← Imos[BS]
       Imos[BS] ← α·Ptex + (1 − α)·Iregion//Pixel-level transparency blending
   End if
End for
Iaug ← Imos,Laug ← Lmos
Return Iaug,Laug

3. Experimental Setup and Result Analysis

3.1. Dataset Construction and Feature Analysis

To verify the effectiveness of the CD-Mosaic algorithm in rigorous industrial scenarios and to ensure reproducibility of experiments, this study constructs a public benchmark dataset dedicated to PCB spur defects. This dataset adopts a multi-source aggregation strategy, with raw images sourced from authoritative open-source industrial inspection communities such as DeepPCB and Roboflow. Covering diverse lighting conditions, manufacturing processes, and two typical mixed acquisition resolutions (416 × 416 and 640 × 640), the dataset inherently features cross-source characteristics, providing an ideal experimental verification platform for validating the topological integrity preservation and visual hard example synthesis strategies proposed in this paper.
To build a high-quality training set suitable for micro-defect detection, we implemented a strict data cleaning and standardization process. First, duplicate images were removed through cross-source hash comparison to prevent data leakage. Second, category purification and scale filtering were conducted: all non-spur categories and macroscopic samples with a pixel size exceeding 48px were eliminated, ensuring the dataset focuses on the challenges of micro-scale and sparse features. After secondary verification by experts, 2331 high-quality samples were finally retained. Currently, this dataset has been open-sourced at https://github.com/laisifan/PCB-spur-dataSet (accessed on 1 February 2026). The dataset is randomly divided into a training set (1631 images, containing 4365 defects), a validation set (466 images, containing 1273 defects), and a test set (234 images, containing 659 defects).
To quantify the detection difficulty of the dataset, this paper refers to the definition criteria of MS COCO and AI-TOD [36] and divides the defects into three intervals according to the maximum side length: extremely tiny (<16 px), tiny (16–32 px), and medium (>32 px). The statistical results shown in Figure 4 profoundly reveal the extreme characteristics of this dataset in terms of scale and density. First, from the histogram distribution at the top of Figure 4, it can be seen that the average width and height of the defects are only 18.7 px and 18.5 px, respectively, and the pixel area of the vast majority of samples is below 32 × 32 px, which means that the feature information is extremely scarce in physical imaging. More seriously, the data presents a significantly skewed distribution. The pie chart at the bottom of Figure 4 shows that the proportion of extremely tiny samples is as high as 15.9%, while that of medium samples is only 6.8%. This distribution skewed towards extremely small scales is also a recognized common challenge in the current industrial defect detection field [37]. As Xu et al. [29] confirmed, when the target size is less than 16 pixels, the multi-layer downsampling mechanism of conventional CNN can easily lead to the complete disappearance of features in the deep feature maps. In addition, the low average defect density of ≤3 per single image means that the background area occupies most of the pixel space. This sparse feature density causes the model to be prone to a high false-alarm rate due to the dominance of negative samples, further increasing detection difficulty.
Figure 4. Statistical chart of defect scale distribution in the dataset.
The above statistical results reveal the adaptability bottleneck of the original Mosaic augmentation in micro-defect detection and form the design basis for CD-Mosaic. Specifically, given the scale skew characteristic, where the proportion of extremely small samples reaches up to 15.9%, the risk of feature truncation from random cropping doubles. Therefore, the mechanisms of “intelligent sampling” and “dynamic integrity verification” need to be introduced to ensure the exposure frequency and geometric integrity of extremely small-scale samples during training. Meanwhile, in response to the characteristics of feature sparsity and topological dependence, this paper introduces a dual-granularity visual perturbation strategy. By constructing challenging scenarios with foreign object aliasing and low signal-to-noise ratio using background hard masks and defect soft masks, the model is forced to focus on the core topological structure rather than simple textures under complex interference, thus effectively suppressing the overfitting risk caused by sparse features.

3.2. Experimental Configuration

To ensure the fairness and reproducibility of experiments, all experiments were conducted on a unified hardware and software platform. The hardware was equipped with an Intel Xeon Platinum 8352V CPU and an NVIDIA RTX 4090 (24 GB) GPU. The software environment was based on Ubuntu 20.04, using the PyTorch 2.1.2 framework and the CUDA 11.8 acceleration library.
To adjust data augmentation hyperparameters and accurately evaluate the independent gain of CD-Mosaic, we strictly follow the single-variable principle to design comparative experiments. Considering that mixing strategies such as Mixup and CutMix [38] can easily disrupt the circuit topology logic, we set their triggering probabilities to zero throughout the experiment. The baseline model retains only the native Mosaic (with a probability set to 1.0), whereas the experimental group replaces it with CD-Mosaic. Through strict control of variables, we ensure that the final performance improvement is primarily attributable to the geometric and texture optimization mechanisms proposed in this paper, rather than the superposition effect of other augmentation methods. The detailed configuration of key parameters is shown in Table 2.
Table 2. Configuration table of key hyperparameters for the experiment.

3.3. Evaluation Indicators

To comprehensively evaluate model performance for detecting minor defects in industrial PCBs, this study follows the MS COCO standard evaluation system and combines the actual deployment requirements of the Automated Optical Inspection (AOI) system. Precision, Recall, mean Average Precision (mAP), and Frames Per Second (FPSs) are selected as the core indicators.

3.3.1. Precision and Recall

In the industrial defect detection scenario, these two indicators respectively characterize the model’s ability to suppress negative samples and its ability to cover positive samples.
Precision (P): It quantifies the reliability of the model’s prediction results, which is the proportion of true positive samples among all the samples predicted as defective. The calculation formula is as follows:
P = T P T P + F P
Recall rate (R): It quantifies the sensitivity of the model in capturing actual defects, which refers to the proportion of defect samples correctly detected by the model among all the actually existing defect samples.
R = T P T P + F N
Here, TP represents the number of correctly detected defects, FP represents the number of false-alarmed background regions, and FN represents the number of undetected defects. Given the low tolerance for undetected defects in PCB manufacturing, industrial sites typically adhere to the principle of prioritizing high recall. That is, on the premise of ensuring an acceptable false-alarm rate, recall is maximized to prevent the release of functionally defective products.

3.3.2. Mean Average Precision (mAP)

To comprehensively evaluate the model’s detection performance across different confidence thresholds, we adopt the Area Under the Precision–Recall Curve (Average Precision, AP) as the core metric. This study also selects two key indicators, mAP@0.5 and mAP@[0.5:0.95], for multi-dimensional assessment.
mAP@0.5: It calculates the average precision when the IoU threshold is set to 0.5. For PCB micro-defects (e.g., spur defects), due to their extremely small pixel scale, minor offsets in the predicted bounding boxes can cause drastic fluctuations in IoU. Therefore, mAP@0.5 focuses more on evaluating the robustness of the model in defect detection, and it serves as the primary basis for determining the presence of defects in industrial positioning applications. The calculation formula is as follows:
m A P @ 0.5 = ∫ 0 1 P ( R ) d R
mAP@0.5:0.95: It calculates the mean value of mAP across IoU thresholds ranging from 0.5 to 0.95 (with a step size of 0.05). This metric imposes extremely high requirements on the regression accuracy of bounding boxes. Although the IoU for small targets is highly sensitive to location, the introduction of mAP@0.5:0.95 can objectively reflect the upper-limit performance of the model under high-precision positioning requirements. The calculation formula is as follows:
m A P @ 0.5 : 0.95 = 1 | T | ∑ t ∈ T m A P @ t
where T = {0.50, 0.55, 0.60, …, 0.95} denotes the set of IoU thresholds, and ∣T∣ = 10.

3.3.3. F1-Score

Since precision and recall often exhibit a trade-off relationship where one increases at the expense of the other, a single metric cannot fully reflect the comprehensive performance of a model. To strike an optimal balance between the miss detection rate and the false positive rate, we introduce the F1-score as a harmonic mean metric. The F1-score can simultaneously take into account the model’s ability to suppress negative samples and its ability to cover positive samples. In industrial PCB quality inspection, an ideal model should minimize misdetections while avoiding excessive false alarms to reduce the cost of manual re-inspection. A higher F1-score indicates a better comprehensive performance of the model at this equilibrium point. Its calculation formula is as follows:
F 1 - s c o r e = 2 × P + R P × R
where P denotes precision, and R denotes recall.

3.3.4. Scale-Stratified Average Precision (APsmall)

Since the global mAP metric may be inflated by a small number of large-scale samples, thereby masking the model’s true detection performance on micro-targets, this study introduces the scale-stratified metric APsmall defined by the MS COCO standard for specialized evaluation. According to the COCO evaluation protocol, APsmall is defined as the mAP@0.5:0.95 calculated for targets with a pixel area smaller than 32 × 32 (i.e., 1024 pixels).
The specific calculation logic is as follows: First, the test set is filtered based on the pixel area of Ground Truth, retaining only the micro-sample subset that satisfies Area < 1024 px. Subsequently, the average precision across IoU thresholds from 0.5 to 0.95 is computed on this subset. Given that the vast majority of spur defects in the dataset constructed in this study fall into this category (see Figure 4), APsmall serves as a key indicator to measure whether the model truly overcomes the challenge of feature sparsity and achieves accurate perception of micro-targets.

3.3.5. Inference Speed (Frames per Second, FPS)

To evaluate the real-time processing capacity of the model on the industrial production line, we adopt frames per second (FPSs) as the efficiency indicator. The calculation formula covers the entire process time from image preprocessing, model inference, to post-processing of non-maximum suppression (NMS):
F P S = 1000 t p r e + t i n f e r + t n m s
Among them, tpre represents the preprocessing time; tinfer represents the inference time; and tnms represents the post-processing time, all in milliseconds. In actual industrial deployment, FPS ≥ 30 is generally considered sufficient to meet real-time requirements.

3.4. Ablation Study

To precisely quantify the independent contributions and collaborative gains of each core module in the CD-Mosaic framework to the detection performance of PCB micro-defects, we designed a step-by-step ablation experiment in a unified experimental environment (YOLOv11m). The experimental results are shown in Table 3.
Table 3. Results of the ablation experiment on CD-Mosaic components.
First, the geometric optimization mechanism reshaped the recall benchmark of the model (M1 → M2). Upon introducing intelligent sampling and topological integrity verification, the model performance witnessed the most significant improvement, with the Recall rate surging from 77.3% to 83.4% (+6.1%) and mAP@0.5 increasing to 0.885. This substantial leap is attributed to the synergy between feature fidelity and geometric generalization: on one hand, enforcing the topological integrity of dominant samples effectively corrected feature loss caused by the random cropping of the native Mosaic; on the other hand, the strategic retention of an appropriate number of edge-truncated samples served as geometric hard examples, compelling the model to perform inference under incomplete information, thereby enhancing its generalization capability against partial occlusion scenarios. This controlled geometric distribution established the foundation for high recall in tiny object detection.
Building on this, the dual-granularity visual perturbation strategy achieved bidirectional optimization of precision and recall (M2 → M3/M4). The hard mask in the background area (M3) simulated foreign object interference, prompting the model to learn more robust background suppression capabilities. This pushed the Precision to the group’s highest at 95.2%, effectively reducing false alarms caused by complex textures. Meanwhile, the soft mask in the defect area (M4) was used to synthesize a visual hard example under a low-SNR imaging environment. This enabled the model to more accurately capture fuzzy defects, further pushing the Recall to 85.8%.
The final CD-Mosaic complete solution (M5) integrated all the above advantages, achieving the best balance between “High Recall (86.1%)” and “High Precision (95.0%)”, with the comprehensive F1-score reaching 0.903 (+6.2% compared to the baseline). Notably, the scale-stratified metric APsmall (0.534) slightly exceeds the global metric mAP@0.5:0.95 (0.529). This phenomenon is primarily attributed to the extreme scale skewness of the dataset (where micro-defects account for 92.8%), causing the global metric to be statistically dominated by the performance on micro-samples. Building on this, thanks to CD-Mosaic’s targeted enhancement of topological integrity and weak features, the model further consolidated its detection superiority on this dominant category, thereby effectively adapting to the long-tail distribution.
Furthermore, this performance leap comes with the industrial advantage of “zero inference cost”. In terms of inference efficiency, M5 achieves an FPS of 84.9, showing only a negligible statistical fluctuation of approximately 0.7% compared to the baseline (85.5). This is because all complex computations in CD-Mosaic (sampling, verification, and mask generation) are completely pre-positioned in the data pre-processing pipeline during the training phase, without altering the backbone network structure or inference logic of YOLOv11m, perfectly meeting the stringent requirements of industrial scenarios for real-time detection.

3.5. Comparative Evaluation with Mainstream Enhancement Strategies and Model Scales

To verify the superiority of the CD-Mosaic algorithm and its applicability under different computing power constraints, this section conducts comparative experiments from two dimensions: different enhancement methods and different model scales.

3.5.1. Comparison with Mainstream Data Augmentation Methods

To verify that the context-aware and domain-consistent data augmentation strategy proposed in this paper outperforms mainstream random augmentation paradigms, we compared CD-Mosaic with three representative methods in the object detection field, namely CutMix, GridMask, and Copy-Paste (detailed results are shown in Table 4; all experiments were conducted using YOLOv11m). It should be noted that for GridMask, we specifically adopted an optimized configuration tailored for small objects (grid cell size d ∈ [20, 50], retention rate r = 0.6, and random rotation enabled) to ensure the fairness of the comparison.
Table 4. Performance comparison of CD-Mosaic with mainstream data augmentation methods.
The experimental results demonstrate that general data augmentation strategies exhibit significant limitations in the task of PCB micro-defect detection. Specifically, CutMix (M2) yields the worst performance, with its mAP@0.5 dropping significantly to 0.813 (−2.7%) compared with the baseline. The root cause lies in the fact that CutMix’s random large-block occlusion mechanism is highly prone to positive sample erasure when dealing with sparsely distributed tiny targets, resulting in the physical loss of critical training information. Benefiting from its structural regularization effect, GridMask (M3) achieves a slight improvement in mAP@0.5 (+0.8%) relative to the baseline. However, it is noteworthy that its precision anomalously dropped to 91.5%, which is lower than that of the baseline. This indicates that the black grid lines introduce a large number of unnatural spurious edges into PCB images, severing the originally connected circuit topology and causing the model to easily misclassify these edges as circuit fractures or structural abnormalities. By directly increasing the density of positive samples, Copy-Paste (M4) effectively boosts the recall rate to 80.6% and mAP@0.5 to 0.875; nevertheless, its performance remains significantly inferior to that of CD-Mosaic. This performance gap stems from the fact that Copy-Paste ignores the physical constraint that spur defects must be attached to conductive traces, blindly pasting spur defects onto non-conductive areas, which violates the circuit’s physical logic that defects are dependent on traces. Such counterintuitive samples mislead the model into learning incorrect background dependencies, thereby limiting its upper performance bound.
The proposed CD-Mosaic (M5) in this paper achieves the optimal results in mAP@0.5 (0.923), mAP@0.5:0.95 (0.529), precision (95.0%), recall (86.1%), and F1-score (0.903), thanks to the balanced feature fidelity and geometric generalization as well as the simulation of real imaging interference via dual-granularity masks. This fully proves that, in the scenario of precision industrial detection, constructing samples with topology consistency and domain consistency that conform to physical laws is more crucial than blind data augmentation.

3.5.2. Efficiency Trade-Off Across Model Scales

To identify the backbone network most suitable for industrial field deployment, we applied CD-Mosaic to the Nano, Medium, and Large versions of YOLOv11, aiming to find the optimal balance between detection accuracy and inference speed (see Table 5 for details).
Table 5. Performance comparison across model scales based on CD-Mosaic.
The experimental results exhibit a significant inverted U-shaped distribution, revealing the nonlinear sensitivity of micro-defect detection to model capacity. Specifically, although the lightweight YOLOv11n achieves an extremely fast inference speed of 98.0 FPS, its mAP@0.5 is only 0.862, indicating that the feature extraction ability of the shallow network is insufficient to capture the extremely low contrast and complex topological dependence of spur defects, causing the model to fall into the underfitting bottleneck. Conversely, the YOLOv11l with the largest number of parameters does not deliver the expected performance leap. Its accuracy (0.915) is slightly lower than that of the Medium version, and the increase in computational overhead causes the FPS to drop significantly to 57.8. This phenomenon of diminishing marginal effects indicates that simply increasing the number of parameters cannot linearly improve the representation ability of micro-targets but instead introduces unnecessary computational delays. Overall, YOLOv11m achieves an optimal balance between feature expression ability and computational efficiency with the highest accuracy of 0.923 and a real-time inference speed of 84.9 FPS. It not only effectively avoids the underfitting risk of shallow networks but also avoids the computational redundancy of deep networks. Therefore, it is established as the final deployment model of this system.

3.6. Visual Analysis

3.6.1. Qualitative Detection Results and Analysis of Missed Detections

The improvement in quantitative metrics is intuitively reflected in the enhanced ability of the model to capture typical “difficult samples” in industrial settings. To validate the robustness of CD-Mosaic in real-world scenarios, we selected the high-density wiring background and low-contrast texture interference, where the original Mosaic model is prone to failure, for a visual comparative analysis (as shown in Figure 5).
Figure 5. Comparison diagram of qualitative detection results.
First, in the complex topological background (the first row in Figure 5), the baseline model loses key physical connections between defects and circuits due to random cropping, causing features to lack semantic support in dense traces and leading to missed detections. In contrast, CD-Mosaic enforces the preservation of the geometric context of defects and their neighborhoods through topological integrity verification. This enables the model to successfully establish the correct logical association that spurs must be attached to conductors, thus accurately locating targets even in extremely complex wiring backgrounds.
Secondly, in the texture interference scenario (the second row of Figure 5), when faced with dirt coverage or uneven illumination, the baseline model’s detection confidence drops significantly or even fails. In contrast, CD-Mosaic benefits from the dual-granularity visual perturbation strategy. By introducing the background hard mask and the defect soft mask during training, it simulates real imaging interference. This mechanism drives the model to skip surface-texture noise and instead focus on more essential edge gradient anomalies, ensuring stable detection under low signal-to-noise ratio and local occlusion conditions.

3.6.2. Comparison of P-R Curve Characteristics

The envelope shape of the P-R curve intuitively reflects the model’s ability to balance recall and precision. As shown in Figure 6, compared with the baseline model (Figure 6a), the curve of the CD-Mosaic model (Figure 6b) exhibits a more plump convex feature, and the area under the curve (mAP@0.5) increases from 0.840 of the baseline to 0.923. Notably, there is a significant right shift in the performance inflection point. The precision of the baseline model drops sharply when Recall > 0.7, indicating that it must significantly sacrifice the confidence to detect difficult samples. In contrast, CD-Mosaic shifts the inflection point to Recall ≈ 0.9 and maintains high precision in the critical interval [0.7, 0.9], which proves that the model’s discriminative confidence for tiny and blurred defects is significantly enhanced.
Figure 6. Comparison of P–R curve features of the models.

3.6.3. Analysis of Learning Curve and Convergence Process

To explore the profound impact of the CD-Mosaic strategy on the model optimization process, Figure 7 presents a comparison of the full-cycle learning curves. Focusing on the val/box_loss curve, the baseline model exhibits obvious numerical oscillations in the late training stage (150–300 Epochs), which reveals the “topological fracture” problem caused by the native Mosaic random cropping. That is, the physical loss of geometric features leads to label noise, interfering with the gradient stability of the regression task. In contrast, CD-Mosaic eliminates invalid samples through a topological integrity verification mechanism, and its Loss curve shows significant smoothness and monotonic convergence characteristics, demonstrating that the improvement of sample quality effectively reduces the fitting difficulty of the model. Meanwhile, in the metrics/mAP50(b) and metrics/recall(b) indicators, CD-Mosaic shows faster convergence efficiency and a higher performance ceiling. This phenomenon is attributed to the visually hard examples synthesized by the dual-granularity visual perturbation strategy. By introducing simulated occlusion and low signal-to-noise ratio samples in the early training stage, the model’s ability to extract weak edge gradients is effectively improved, thus significantly shortening the iteration cycle from feature learning to optimal convergence.
Figure 7. Comparison of the evolution of training losses and performance metrics between the baseline model and CD-Mosaic.

4. Discussion

The above experimental results demonstrate that mitigating blind randomness in data augmentation is crucial for improving the detection performance of tiny industrial defects. Standard data augmentation methods (e.g., native Mosaic and Cutout) often fail due to their disruption of circuit topological dependencies or photometric consistency. From a mechanistic perspective, the advantage of CD-Mosaic lies in the synergistic optimization of geometric and texture dimensions. In the geometric dimension, the intelligent sampling and integrity verification mechanism constructs a controlled distribution characterized by “feature fidelity as the dominant component (70%) and truncated hard cases as the supplementary component (30%)”. This dynamic balance not only clarifies the gradient direction for model optimization and avoids semantic ambiguity caused by geometric incompleteness but also enhances the model’s generalization capability in local occlusion scenarios through an appropriate number of hard cases. In the texture dimension, the dual-granularity visual perturbation strategy superimposes controlled interference on the valid topological structure. Hard masks simulate foreign object occlusion to improve background suppression capability, while soft masks simulate low signal-to-noise ratio (SNR) environments, prompting convolution kernels to bypass surface-texture noise and instead optimize perception weights for weak edge gradients. This dynamic balance between topological integrity and geometric generalization, combined with anti-interference enhancement in the texture dimension, significantly alleviates the bottlenecks of high miss-detection rate and localization difficulty for tiny targets without introducing additional computational costs.
Furthermore, the core principles of the CD-Mosaic framework hold great potential for extension to wafer defect detection, another critical domain in semiconductor manufacturing. Similar to PCB inspection, wafer inspection faces the dual challenges of identifying extremely minute features (e.g., micro-scratches, particle contamination) and handling highly imbalanced data distributions. The Topological Integrity Verification mechanism proposed in this paper is highly relevant to the periodic arrangement of wafer dies. By adjusting this mechanism, a training distribution characterized by dominant intact dies with coexisting truncated hard examples can be constructed: during random cropping, it prioritizes preserving intact die structures to guide the model in learning periodic features, while strategically retaining a portion of edge-truncated samples to enhance the model’s robustness in identifying incomplete dies located at the wafer periphery or field-of-view boundaries. Moreover, the Dual-Granularity Visual Perturbation strategy in this paper is highly consistent with common wafer imaging mechanisms. Hard Masks can effectively simulate surface particle contamination (e.g., dust or silicon debris), while Soft Masks can mimic local focusing errors or thin-film interference variations caused by wafer warpage. Consequently, CD-Mosaic offers a promising general-purpose solution for micro-defect detection tasks across the broader electronics manufacturing industry.
Despite significant performance improvements in PCB micro-defect detection, CD-Mosaic still has certain limitations regarding defect types and application scenarios. First, this method exhibits scale sensitivity. The Topological Integrity Verification mechanism is specifically optimized for micro-defects with sparse features. For macro-defects (e.g., large-area board damage or extensive contamination), strict integrity constraints may excessively restrict the freedom of random cropping, thereby potentially reducing the diversity of geometric augmentation. Second, the algorithm relies on domain-specific geometric priors. The settings of the protection margin m and integrity threshold τ are derived from the statistical characteristics of PCB spurs. When migrating this method to other industrial scenarios with significantly different defect scales or aspect ratios (e.g., textile fabric inspection or steel surface crack detection), it is necessary to conduct re-statistical analysis on the dataset to recalibrate these hyperparameters. Finally, although the inference cost is zero, the dynamic trial-and-error verification process during the training phase introduces a slight increase in data preprocessing time compared with the original Mosaic, which may affect training efficiency on ultra-large-scale datasets.
Building on current achievements in data augmentation, future research will advance in two areas: model structure optimization and system deployment. On one hand, we will explore the collaborative design of multi-scale feature fusion modules and dynamic sparse attention mechanisms. Unlike traditional static attention, dynamic mechanisms can adaptively optimize the receptive field and capture long-range dependencies. This design aims to work synergistically with CD-Mosaic, further improving the feature extraction capability for multi-category tiny defects such as micro-cracks, and verifying the model’s generalization ability in scenarios where complex defects coexist [39]. On the other hand, we intend to combine model pruning and knowledge distillation technologies to reduce the algorithm’s reliance on high-computing hardware [40] and develop a visual interactive interface to promote the closed-loop deployment and practical application of intelligent detection systems on embedded edge terminals.

5. Conclusions

To address the challenges of feature sparsity and topological dependence in industrial PCB micro-defect detection, this paper proposes a context-aware and domain-consistent data augmentation framework named CD-Mosaic. This method mitigates the randomness of traditional augmentation strategies by constructing geometrically controlled distributions and simulating industrial imaging interference in the texture dimension, thereby establishing a high-quality training distribution tailored to the imaging characteristics of industrial micro-targets.
Experimental results on an industrial-grade dataset containing 2331 images validate the superiority of the proposed method. The YOLOv11m model, when integrated with CD-Mosaic, achieves substantial performance improvements across multiple dimensions: mAP@0.5 increased to 0.923 (+8.3%), and the comprehensive F1-score reached 0.903 (+6.2%). Notably, regarding high-precision localization and micro-object perception, mAP@0.5:0.95 and the scale-stratified metric APsmall improved to 0.529 (+3.0%) and 0.534 (+3.3%), respectively. Furthermore, the model achieved a high Recall of 86.1% (+8.8%) while maintaining a Precision of 95.0% (+2.7%). These results outperform both the baseline model and other mainstream data augmentation methods, effectively breaking through the bottlenecks of high miss-rates and poor localization accuracy for micro-defects. Importantly, as a pure data-side optimization scheme, CD-Mosaic shifts all computational overhead to the training preprocessing phase while maintaining an inference speed of 84.9 FPS. It thus meets the real-time requirements of industrial production lines without incurring any additional deployment costs.

Author Contributions

Methodology, formal analysis, and supervision, S.G.; software, validation, data curation, visualization, writing—original draft preparation, and writing—review and editing, S.L.; investigation and resources, X.G.; funding acquisition, J.L.; project administration, K.F. All authors have read and agreed to the published version of the manuscript.

Funding

This research was funded by the Shanxi Province Fundamental Research Program (No. 202303021221114).

Data Availability Statement

The dataset constructed and used in this study is publicly available on GitHub at https://github.com/laisifan/PCB-spur-dataSet (v1.0) (accessed on 1 February 2026). This dataset was derived and aggregated from open-source contributions, including the DeepPCB dataset [41] and public projects hosted on Roboflow [42,43].

Conflicts of Interest

The authors declare no conflicts of interest.

References

  1. Chen, X.; Wu, Y.; He, X.; Ming, W. A Comprehensive Review of Deep Learning-Based PCB Defect Detection. IEEE Access 2023, 11, 139017–139038. [Google Scholar] [CrossRef] [Scilit]
  2. Tang, J.; Wang, Z.; Zhang, H.; Li, H.; Wu, P.; Zeng, N. A Lightweight Surface Defect Detection Framework Combined with Dual-Domain Attention Mechanism. Expert Syst. Appl. 2024, 238, 121726. [Google Scholar] [CrossRef] [Scilit]
  3. Li, K.; Zhong, X.; Han, Y. A High-Performance Small Target Defect Detection Method for PCB Boards Based on a Novel YOLO-DFA Algorithm. IEEE Trans. Instrum. Meas. 2025, 74, 2008312. [Google Scholar] [CrossRef] [Scilit]
  4. Yang, J.; Li, S.; Wang, Z.; Dong, H.; Wang, J.; Tang, S. Using Deep Learning to Detect Defects in Manufacturing: A Comprehensive Survey and Current Challenges. Materials 2020, 13, 5755. [Google Scholar] [CrossRef] [Scilit]
  5. Ling, Q.; Isa, N.A.M. Printed Circuit Board Defect Detection Methods Based on Image Processing, Machine Learning and Deep Learning: A Survey. IEEE Access 2023, 11, 15921–15944. [Google Scholar] [CrossRef] [Scilit]
  6. Terven, J.; Córdova-Esparza, D.-M.; Romero-González, J.-A. A Comprehensive Review of YOLO Architectures in Computer Vision: From YOLOv1 to YOLOv8 and YOLO-NAS. Mach. Learn. Knowl. Extr. 2023, 5, 1680–1716. [Google Scholar] [CrossRef] [Scilit]
  7. Ma, S.; Zhao, X.; Wan, L.; Zhang, Y.; Gao, H. A Lightweight Algorithm for Steel Surface Defect Detection Using Improved YOLOv8. Sci. Rep. 2025, 15, 8966. [Google Scholar] [CrossRef] [Scilit]
  8. Yao, L.; Zhao, B.; Wang, X.; Mei, S.; Chi, Y. A Detection Algorithm for Surface Defects of Printed Circuit Board Based on Improved YOLOv8. IEEE Access 2024, 12, 170227–170242. [Google Scholar] [CrossRef] [Scilit]
  9. Czimmermann, T.; Ciuti, G.; Milazzo, M.; Chiurazzi, M.; Roccella, S.; Oddo, C.M.; Dario, P. Visual-Based Defect Detection and Classification Approaches for Industrial Applications—A SURVEY. Sensors 2020, 20, 1459. [Google Scholar] [CrossRef] [Scilit] [PubMed]
  10. Ultralytics Ultralytics YOLO11. Available online: https://docs.ultralytics.com/models/yolo11/ (accessed on 20 December 2025).
  11. Tang, J.; Liu, S.; Zhao, D.; Tang, L.; Zou, W.; Zheng, B. PCB-YOLO: An Improved Detection Algorithm of PCB Surface Defects Based on YOLOv5. Sustainability 2023, 15, 5963. [Google Scholar] [CrossRef] [Scilit]
  12. Xiao, G.; Hou, S.; Zhou, H. PCB Defect Detection Algorithm Based on CDI-YOLO. Sci. Rep. 2024, 14, 7351. [Google Scholar] [CrossRef] [Scilit] [PubMed]
  13. Luo, Y.; Ling, J.; Chen, F.; Zhang, H.; Xiao, X.; Lu, N. Weld Defect Segmentation and Detection Using Semi-Supervised Transfer Learning-Based Generative Adversarial Networks. Nondestruct. Test. Eval. 2025, 1, 2548374. [Google Scholar] [CrossRef] [Scilit]
  14. Köhler, M.; Eisenbach, M.; Gross, H.-M. Few-Shot Object Detection: A Comprehensive Survey. IEEE Trans. Neural Netw. Learn. Syst. 2024, 35, 11958–11978. [Google Scholar] [CrossRef] [Scilit]
  15. Zhang, Y.; Kang, B.; Hooi, B.; Yan, S.; Feng, J. Deep Long-Tailed Learning: A Survey. IEEE Trans. Pattern Anal. Mach. Intell. 2023, 45, 10795–10816. [Google Scholar] [CrossRef] [Scilit]
  16. Xu, M.; Yoon, S.; Fuentes, A.; Park, D.S. A Comprehensive Survey of Image Augmentation Techniques for Deep Learning. Pattern Recognit. 2023, 137, 109347. [Google Scholar] [CrossRef] [Scilit]
  17. Bochkovskiy, A.; Wang, C.-Y.; Liao, H.-Y.M. YOLOv4: Optimal Speed and Accuracy of Object Detection. arXiv 2020, arXiv:2004.10934. [Google Scholar] [CrossRef] [Scilit]
  18. Lv, S.; Ouyang, B.; Deng, Z.; Liang, T.; Jiang, S.; Zhang, K.; Chen, J.; Li, Z. A Dataset for Deep Learning Based Detection of Printed Circuit Board Surface Defect. Sci. Data 2024, 11, 811. [Google Scholar] [CrossRef] [Scilit] [PubMed]
  19. Song, H.; Kim, M.; Park, D.; Shin, Y.; Lee, J.-G. Learning From Noisy Labels With Deep Neural Networks: A Survey. IEEE Trans. Neural Netw. Learn. Syst. 2023, 34, 8135–8153. [Google Scholar] [CrossRef] [Scilit]
  20. Zhang, H.; Cisse, M.; Dauphin, Y.N.; Lopez-Paz, D. Mixup: Beyond Empirical Risk Minimization. In Proceedings of the International Conference on Learning Representations (ICLR), Vancouver, BC, Canada, 30 April–3 May 2018. [Google Scholar]
  21. Summers, C.; Dinneen, M.J. Improved Mixed-Example Data Augmentation. In Proceedings of the 2019 IEEE Winter Conference on Applications of Computer Vision (WACV), Honolulu, HI, USA, 7–11 January 2019; pp. 1262–1270. [Google Scholar]
  22. DeVries, T.; Taylor, G.W. Improved Regularization of Convolutional Neural Networks with Cutout. arXiv 2017, arXiv:1708.04552. [Google Scholar] [CrossRef] [Scilit]
  23. Chen, P.; Liu, S.; Zhao, H.; Wang, X.; Jia, J. GridMask Data Augmentation. arXiv 2020, arXiv:2001.04086. [Google Scholar]
  24. Geirhos, R.; Rubisch, P.; Michaelis, C.; Bethge, M.; Wichmann, F.A.; Brendel, W. ImageNet-Trained CNNs Are Biased towards Texture; Increasing Shape Bias Improves Accuracy and Robustness. arXiv 2018, arXiv:1811.12231. [Google Scholar]
  25. Ghiasi, G.; Cui, Y.; Srinivas, A.; Qian, R.; Lin, T.-Y.; Cubuk, E.D.; Le, Q.V.; Zoph, B. Simple Copy-Paste Is a Strong Data Augmentation Method for Instance Segmentation. In Proceedings of the 2021 IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR), Nashville, TN, USA, 19–25 June 2021; pp. 2917–2927. [Google Scholar]
  26. Gordienko, Y.; Rokovyi, O.; Alienin, O.; Stirenko, S. Context-Aware Data Augmentation for Efficient Object Detection by UAV Surveillance. In Proceedings of the 2022 10th International Symposium on Digital Forensics and Security (ISDFS), Istanbul, Turkey, 6–7 June 2022; pp. 1–6. [Google Scholar]
  27. Wang, Y.; Chung, S.-H.; Khan, W.A.; Wang, T.; Xu, D.J. ALADA: A Lite Automatic Data Augmentation Framework for Industrial Defect Detection. Adv. Eng. Inform. 2023, 58, 102205. [Google Scholar] [CrossRef] [Scilit]
  28. Cheng, G.; Wang, J.; Li, K.; Xie, X.; Lang, C.; Yao, Y.; Han, J. Anchor-Free Oriented Proposal Generator for Object Detection. IEEE Trans. Geosci. Remote Sens. 2022, 60, 3183022. [Google Scholar] [CrossRef] [Scilit]
  29. Xu, C.; Wang, J.; Yang, W.; Yu, H.; Yu, L.; Xia, G.-S. Detecting Tiny Objects in Aerial Images: A Normalized Wasserstein Distance and a New Benchmark. ISPRS J. Photogramm. Remote Sens. 2022, 190, 79–93. [Google Scholar] [CrossRef] [Scilit]
  30. Lin, T.-Y.; Maire, M.; Belongie, S.; Hays, J.; Perona, P.; Ramanan, D.; Dollár, P.; Zitnick, C.L. Microsoft COCO: Common Objects in Context. In Proceedings of the Computer Vision—ECCV 2014; Fleet, D., Pajdla, T., Schiele, B., Tuytelaars, T., Eds.; Springer International Publishing: Cham, Switzerland, 2014; pp. 740–755. [Google Scholar]
  31. Hua, W.; Chen, Q. A Survey of Small Object Detection Based on Deep Learning in Aerial Images. Artif. Intell. Rev. 2025, 58, 162. [Google Scholar] [CrossRef] [Scilit]
  32. Yu, X.; Han-Xiong, L.; Yang, H. PCB Defect Detection Model Based on Intrinsic Feature Decomposition and Multilevel Fusion Against Image Uncertainty. IEEE Sens. J. 2024, 24, 19497–19505. [Google Scholar] [CrossRef] [Scilit]
  33. Zeiler, M.D.; Fergus, R. Visualizing and Understanding Convolutional Networks. In Proceedings of the Computer Vision—ECCV 2014; Fleet, D., Pajdla, T., Schiele, B., Tuytelaars, T., Eds.; Springer International Publishing: Cham, Switzerland, 2014; pp. 818–833. [Google Scholar]
  34. Simonyan, K.; Vedaldi, A.; Zisserman, A. Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps. In Proceedings of the 2nd International Conference on Learning Representations, ICLR 2014, Banff, AB, Canada, 14–16 April 2014; Bengio, Y., LeCun, Y., Eds.; Workshop Track Proceedings; ICLR: Banff, AB, Canada, 2014. [Google Scholar]
  35. Goodfellow, I.J.; Shlens, J.; Szegedy, C. Explaining and Harnessing Adversarial Examples. In Proceedings of the International Conference on Learning Representations (ICLR), San Diego, CA, USA, 7–9 May 2015; ICLR: San Diego, CA, USA, 2015. [Google Scholar]
  36. Wang, J.; Yang, W.; Guo, H.; Zhang, R.; Xia, G.-S. Tiny Object Detection in Aerial Images. In Proceedings of the 2020 25th International Conference on Pattern Recognition (ICPR), Milan, Italy, 10–15 January 2021; pp. 3791–3798. [Google Scholar]
  37. Khanam, R.; Hussain, M.; Hill, R.; Allen, P. A Comprehensive Review of Convolutional Neural Networks for Defect Detection in Industrial Applications. IEEE Access 2024, 12, 94250–94295. [Google Scholar] [CrossRef] [Scilit]
  38. Yun, S.; Han, D.; Oh, S.J.; Chun, S.; Choe, J.; Yoo, Y. CutMix: Regularization Strategy to Train Strong Classifiers with Localizable Features. arXiv 2019, arXiv:1905.04899. [Google Scholar] [CrossRef] [Scilit]
  39. Zhang, Y.; Guo, R.; Li, M. Backend-Free Multi-Scale Feature Fusion Network for Defect Detection in Printed Circuit Board Images. J. Real-Time Image Process. 2025, 22, 187. [Google Scholar] [CrossRef] [Scilit]
  40. Yan, H.; Lu, W.; Wu, Y. A Lightweight Microscopic Metal Fracture Classification Method With Structure Pruning and Knowledge Distillation for Embedded Devices. IEEE Trans. Instrum. Meas. 2025, 74, 3509596. [Google Scholar] [CrossRef] [Scilit]
  41. Tang, S.; He, F.; Huang, X.; Yang, J. Online PCB Defect Detector on A New PCB Defect Dataset. arXiv 2019, arXiv:1902.06197. [Google Scholar] [CrossRef] [Scilit]
  42. Tugas Akhir RALR2. Spur-Acjsu Dataset. Available online: https://universe.roboflow.com/tugas-akhir-ralr2/spur-acjsu (accessed on 23 January 2026).
  43. Detección por Defecto. PCB Spur D D Dataset. Available online: https://universe.roboflow.com/deteccin-por-defecto/pcb-spur-d-d (accessed on 23 January 2026).
Disclaimer/Publisher’s Note: The statements, opinions and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content.

Article Metrics

Citations

Article Access Statistics

Multiple requests from the same IP address are counted as one view.