Editor’s introduction
The study focuses on ImbDef-GAN, a generative model designed to produce realistic defect images in scenarios where defective samples are scarce. It compares generated defect images to real ones using KID and LPIPS metrics, which assess distributional differences and perceptual quality, respectively. The model generates background images and defect features separately, then combines them to create defect images with more natural boundaries and better alignment to their masks. A mask-aware discriminator and additional losses ensure structural consistency. The research shows that when generated data are used to train a defect detector, performance improves, as measured by mAP@0.5. Evaluation relies on KID and LPIPS, which are considered more stable than FID in few-sample settings due to their unbiased nature in distributional comparison.
Introduction
Transformation-based approaches apply operations such as scaling, rotation, translation, and flipping to augment the dataset and may also paste cropped defect patches onto background images. Although straightforward to implement, these methods struggle to capture the complexity of real defects, and the resulting defects often lack realism. With advances in deep learning, numerous methods for generating industrial surface defect images have emerged and can be broadly categorized into diffusion-based approaches and GAN-based approaches. Diffusion models, particularly denoising diffusion probabilistic models (DDPMs), with DDPMs commonly adopted as a diffusion baseline due to stable training under a likelihood-based objective, relatively comprehensive mode coverage, and strong perceptual quality on image-generation benchmarks, comprise two processes: (i) a forward diffusion that progressively adds Gaussian noise until the signal approaches random noise; and (ii) a reverse generative process that removes noise stepwise to synthesize an image. However, the iterative denoising schedule yields low sampling efficiency. Without task-specific conditioning or edge-aware objectives, DDPMs may produce softened boundaries between defects and the background and less faithful high-frequency local textures. Generative adversarial networks (GANs) and their variants leverage adversarial learning and are widely used for image generation. StyleGAN3 delivers state-of-the-art, high resolution image generation with fine grained texture fidelity and realistic structural detail, while its alias-free architecture improves geometric consistency and reduces texture artifacts. However, the scarcity of defect samples constrains the ability of GAN models to learn faithful defect distributions in this domain.
In industrial production, background images are abundant, whereas defect images are scarce because such images occur infrequently and are costly to acquire. This leads to severe class imbalance, and defects often exhibit complex, irregular structures. Although recent approaches, including DFMGAN, AnomalyDiffusion, and related methods, can produce visually plausible defect images, several limitations remain: (i) generated defect patterns are often overly similar and fail to capture the diversity observed in production settings; (ii) edge details around defect regions are frequently lost, undermining realism; (iii) misalignment may occur between a generated defect and its corresponding mask, degrading the quality of the generated regions; and (iv) defects may appear in invalid areas, such as outside the product region. Consequently, generating realistic and diverse defect images under highly imbalanced conditions, in which background images far outnumber defect images, remains an open challenge.
Few Sample Image Generation
When training data are extremely scarce (fewer than 10 images), models readily overfit and the generated images closely resemble the training samples. A common remedy is transfer learning, which adapts a model pretrained on a large source domain to a small target domain. FreezeD mitigates overfitting during fine tuning by freezing higher-level weights of the pretrained GAN discriminator and combining this with regularization and data augmentation. WeditGAN learns fixed offsets in the StyleGAN latent space to construct a target latent space, preventing mode collapse and overfitting with minimal fine tuning. AdAM introduces adaptation-aware kernel modulation: it identifies salient convolutional kernels via importance estimation and applies low rank modulation during fine tuning to preserve and adapt source domain knowledge, yielding stable, high quality few-shot image generation.
In contrast, few-shot customization on pretrained diffusion models has attracted wide attention. Textual Inversion learns a compact set of “pseudo-token” embeddings that encode novel concepts in the text space, balancing faithfulness and editability and improving visual fidelity and editing robustness. DreamBooth personalizes text to image diffusion models by fine tuning a pretrained model and introducing a class specific prior preservation loss generated by the model itself, enabling high-quality and diverse images across varied scenes, poses, and lighting conditions. Although these approaches can produce realistic images, they lack mechanisms for precise defect localization and for high quality mask generation. This limitation hinders the creation of accurate masks for downstream detection or segmentation, which is essential for anomaly image generation. Our method instead generates diverse, high-quality defect images together with their corresponding masks under few-shot conditions.
Defect Image Generation
The scarcity of defective samples has motivated research into defect image generation. DeVries et al. simulate defects by introducing random cutouts (masked regions) into defect-free images. CutPaste copies a patch from a defect-free image and pastes it at a new location to create a synthetic anomaly. Similarly, Crop&Paste crops defect regions from defect images and pastes them onto other images. However, these traditional approaches produce only a limited number of samples that scale with the dataset size. They do not introduce new defect modes. Instead, they transplant existing defects onto different images.
For deep learning approaches, defect image generation can be broadly grouped into diffusion and GAN methods. Diffusion models are widely used for their strong generalization ability. Wang et al. propose a progressive training diffusion model for defect image generation that improves training stability and produces diverse, high quality defect images. DualAnoDiff employs two interrelated diffusion branches to jointly generate the whole image and the anomaly part, improving realism and diversity in the few-shot regime. AnomalyDiffusion, built on a latent diffusion model, introduces Spatial Anomaly Embedding to decouple defect appearance from location and employs Adaptive Attention Reweighting to dynamically upweight low-salience defect regions during generation. Because training focuses on masked regions, fusion between defects and the surrounding background is often inadequate, yielding poor boundary transitions and weak textural consistency. Defects may also be placed in invalid or semantically mismatched background areas, which undermines the realism of the generated images.
GANs and their variants are widely used for a wide range of image-generation tasks because of their strong generative ability. A GAN consists of a generator and a discriminator trained adversarially in a minimax game that approaches a Nash equilibrium. This pressure drives the generator to produce increasingly realistic images. The generator seeks to fool the discriminator by producing images indistinguishable from real data, while the discriminator learns to distinguish generated images from real ones.
Methods
Generative adversarial networks (GANs) require sufficient defect samples to learn the underlying data distribution and to generate novel, high quality defect images. However, because background samples are abundant, whereas defect samples are scarce, GAN training often yields suboptimal image quality and overfits to the few available defect instances. To address this, we propose ImbDef-GAN, which improves defect image generation through a sample imbalance compensation mechanism. ImbDef-GAN mitigates these issues through a two-stage design of “background prior—defect injection”, first learning a background prior from abundant background images to obtain a stable and reusable representation, then freezing the background backbone during defect generation and injecting defect features into the generated background via a mask conditioned residual branch. This localization of trainable parameters to defect regions markedly contracts the effective hypothesis space, curbs overfitting at its source, and enables more effective use of background samples. We (1) exploit abundant background samples to compensate for limited defect data, and (2) jointly learn and fuse representations from defect and background samples to generate realistic defect images.
Defect Image Generation with Background Conditioning
For the same object, defect and background images are approximately drawn from a common underlying distribution, with only sparse deviations confined to the local regions indicated by the defect mask. In real-world scenarios, variations in surface treatments and optical conditions often invalidate the assumption that background and defect images share the same distribution, thereby inducing distributional shifts between them. Nevertheless, ImbDef-GAN remains effective in generating high-quality defects under varying conditions. By conditions defect generation on the background image and applies mask consistency and boundary smoothing constraints to generate defects in a controllable manner, alleviating sample scarcity while preserving background fidelity and natural transitions.
Given that defect masks occupy a small portion of the image, existing matching discriminators tend to attenuate mask cues in later training, leading to spatial misalignment between generated defects and their corresponding masks. To mitigate this issue, a mask-aware matching discriminator is designed to continuously propagate mask information to deep feature layers, thereby strengthening image and mask alignment and improving the accuracy of defect localization. Meanwhile, Edge Structure Loss (ESL) encourages diverse boundary morphology to suppress boundary artifacts and structural monotony and to enhance overall realism; additionally, Region Consistency Loss (RCL) constrains the defect mask to the valid region defined by the background mask, preventing generation outside the object and avoiding invalid placement.
Mask-Aware Matching Discriminator
In defect imagery, the anomalous region typically occupies a small fraction of pixels, so reusing a background-oriented matching discriminator often attenuates mask cues in the final layers and limits precise correspondence between the image and the mask. This motivates the introduction of a mask-aware matching discriminator that forms a four-channel input by concatenating the RGB image with its mask and progressively injects a downsampled mask at each stage.
The minibatch standard deviation (mbstd) module at the discriminator tail enhances the discriminator’s sensitivity to sample diversity. It first partitions the input features according to a specified group size and number of channels, then computes the standard deviation across channel and spatial dimensions within each group, yielding a feature map that captures intra-minibatch statistical fluctuations. This map is concatenated with the original features along the channel dimension and passed to subsequent discriminator layers, which improves sensitivity to variation among generated samples and helps mitigate mode collapse in the generator.
The mask-aware matching discriminator adopts Wasserstein adversarial loss and is optimized with regularization. Working in concert with the StyleGAN3 discriminator during defect image generation, it yields more realistic and diverse images and achieves higher localization accuracy for defect regions.
Edge Structure Loss
The generated defect image is jointly determined by object and defect features. In practice, if defect features exert only a limited influence on the final defect morphology, different defect feature mappings may produce negligible variations, thereby constraining the diversity of generated defects. To prevent weak variations and encourage distinct morphologies under different defect conditions, Edge Structure Loss (ESL) is introduced, inspired by mode seeking. ESL promotes diversity in the space of defect shape and geometry rather than raw intensity, aligning latent perturbations with meaningful structural changes.
ESL employs the Laplacian edge operator to extract edge structure from defect masks, aiming to elevate the discrepancy measure from simple pixel-level differences to structural edge-level differences, thereby guiding the generator to focus more on structural variations in defect morphology. As shown in Equation (11), the edge operator effectively captures boundary variation in masks and further increases the structural diversity of generated defect masks. Although the Laplacian operator is a conventional image processing tool, it remains stable and efficient on defect masks, whose structures are well defined with sharp boundaries. The detailed formulation of ESL is given in Equation (12).
Evaluation Metrics
Defect image generation is primarily evaluated using KID and LPIPS. Because real defect samples are scarce, FID yields biased estimates in few-sample settings, leading to unstable evaluations. By contrast, KID uses an unbiased maximum mean discrepancy (MMD) estimator, offering greater robustness and stability and making it better suited to assessing image quality and diversity in few-shot scenarios. Accordingly, KID is the primary quality metric for reliably reflecting distributional differences between generated and real defect images, with LPIPS providing a complementary perceptual measure.
For each defect category, 5000 samples are generated and compared with the corresponding authentic defect images in the dataset to compute the KID score. A lower KID score indicates that the generated images are closer to real ones in terms of realism and diversity, reflecting higher overall quality.
LPIPS is a metric for measuring perceptual similarity between images and is particularly suited for evaluating the diversity of generated samples. Suppose a given defect category in the dataset contains N images. For 1000 generated images, the evaluation first computes their LPIPS similarity to the closest real image in the dataset and then assigns each generated image to one of the N clusters accordingly. Next, the evaluation obtains the cluster mean LPIPS by averaging over all image pairs within each cluster, and then averages these cluster means to yield the overall mean. A higher cluster-level LPIPS score indicates greater diversity among the generated images. Combining KID and LPIPS provides a more comprehensive evaluation of both the realism and diversity of generated defect images.
Comparative Experiments on Defect Image Generation
Defects generated by Crop&Paste more closely match the real data distribution. Although StyleGAN2 and StyleGAN3 perform well on general image generation, they are less effective with scarce defect data. On hazelnut, the generated defects show overfitting, limited diversity, and inflated structural artifacts. In addition, StyleGAN3 exhibits pronounced color shifts, reducing realism. With limited defect samples, Defect-GAN struggles to capture salient characteristics of defect regions, yielding defects that are insufficiently prominent and overly small, which falls short of practical requirements. DFMGAN offers advantages over these methods, but its defect boundaries remain unnatural. Misalignment between defect masks and generated regions further degrades realism and limits the quality of the generated regions. AnomalyDiffusion achieves greater diversity but lacks realism in defect regions. Generated defects sometimes spill beyond valid areas. The feature disentanglement method based on StyleGAN2-ADA proposed by He et al. generates defect images that closely approximate the appearance of real defects. Our method outperforms existing approaches across multiple categories, mitigating unnatural boundary texture and morphology, misalignment between images and masks, and placement outside valid regions. The generated results align more closely with real defect images in both overall quality and fine grained detail.
Comparative Experiments on Defect Detection
YOLO is a representative single stage, end-to-end detector noted for high throughput and low latency. For defect detection, YOLOv11 enhances multi-scale feature representation and the detection head, markedly improving detection rate and localization accuracy for small scale, low contrast, fine grained defects. Accordingly, we adopt YOLOv11 to assess the gains from the proposed defect image-generation method and evaluate it under different generation strategies. To ensure objectivity and reliability, the test set satisfies three criteria: (i) it is disjoint from all data used for image generation; (ii) it contains only real images, with no generated samples; and (iii) its defect category distribution matches the real world distribution.
Differences in defect-detection performance across datasets are quantified using mean Average Precision (mAP). mAP is the mean of per-class average precision (AP), where each AP is the area under the precision–recall (PR) curve; it summarizes per-class detection performance across categories. Higher mAP indicates better localization and recognition of defects. In our setting, higher mAP suggests that generated defect images preserve spatial placement, show natural boundary transitions, and encode discriminative features, enabling more effective recognition and localization. Accordingly, mean Average Precision (mAP) serves as the primary metric to quantify gains from defect image generation. To assess overall detection performance across categories, mAP@0.5, defined as the mean of average precision computed per class at an IoU threshold of 0.5, is reported.
Conclusions
This work addresses three challenges in defect image generation: unnatural defect boundaries, imprecise alignment between generated images and their masks, and implausible defect placement. Abundant background images together with scarce defect images are leveraged to tackle these issues. We propose ImbDef-GAN, a generative framework that accounts for sample imbalance and integrates defect features into generated background images to generate defect images. First, a lightweight variant of the StyleGAN3 generator is designed to jointly generate the background and its mask, and their consistency is enforced with a matching discriminator. A Progress-coupled Gated Detail Injection module enhances background detail while preserving training stability. Second, a residual branch extracts defect features and blends them with background features under a smoothing coefficient, yielding more natural and gradual defect boundaries. To improve alignment between images and masks, a mask-aware matching discriminator propagates mask information through multilayer feature extraction. We further introduce Edge Structure Loss to emphasize boundary morphology and Region Consistency Loss to suppress defects in invalid background areas. Experiments on the MVTec AD dataset indicate consistent gains in realism and diversity; nevertheless, performance remains sensitive to the quality of the jointly generated background mask, particularly in scenes with ambiguous object boundaries or occlusion. Training a YOLOv11 detector on the generated data yields measurable accuracy gains and reduces both false positives and false negatives. However, in real-world scenarios, the assumption of distributional consistency between defects and backgrounds does not always hold, so localization of tiny defects and fine textures may still be limited under extreme conditions.


