SAFE-YOLO for Casting Defect Detection

I present a lightweight and high-precision detection model, SAFE-YOLO, designed for casting defect detection on edge devices. The motivation for this work comes from the fact that casting defect detection is a critical machine-vision-based automation technology in modern industrial production. Casting defects such as cracks, porosity, shrinkage cavities, sand holes, excess material, and inclusion or abnormal structure can seriously affect subsequent machining, shorten service life, and introduce safety risks for equipment and operators. I therefore focus on building a model that can perform casting defect detection accurately, rapidly, and efficiently under the resource constraints of industrial edge deployment.

Traditional casting defect detection methods mainly rely on manual visual inspection or conventional machine vision pipelines. These pipelines usually include image preprocessing, feature extraction, template matching, and positive-negative sample classification. Although such methods can be useful in controlled environments, they depend heavily on the experience and judgment of inspectors. As a result, the detection rate for casting defects fluctuates significantly, especially for small, low-contrast, or atypical defects such as early micro-cracks and shallow porosity. Manual full inspection is also slow, difficult to synchronize with modern production lines, and costly in terms of human labor. Long periods of intense visual inspection can cause fatigue and further reduce long-term reliability. These limitations motivate the use of deep learning for casting defect detection.

Deep-learning-based defect detection algorithms have gradually replaced many traditional algorithms. They are generally divided into two-stage detectors, such as Mask R-CNN, and one-stage detectors, such as SSD and the YOLO family. Two-stage algorithms are often used for long-distance small-object detection, while one-stage algorithms are preferred for fast recognition and real-time tasks such as insulator fault detection and foreign-object identification. However, applying existing detectors directly to casting defect detection still faces severe challenges. Some models are too heavy for edge devices. Some models improve accuracy but sacrifice inference speed. Others perform well on general datasets but fail to capture the subtle spatial details of casting defects. I therefore construct SAFE-YOLO to balance lightweight design and high precision for casting defect detection.

The main contributions of my work can be summarized as follows. First, I use a SlimNeck structure to optimize the neck network, reducing redundant information and lowering computational complexity. Second, I integrate the SimAM attention mechanism at the connection positions between the backbone network and the neck network. This improves detection performance without increasing computational load or memory usage. Third, I introduce a feature re-extraction module based on space-to-depth convolution, abbreviated as SPDConv, to replace traditional downsampling operations. This preserves spatial resolution and captures subtle casting defect features more precisely. Fourth, I construct a Wise-IoUv3 loss function to accelerate model convergence and improve bounding-box regression quality. Experimental results show that, compared with the YOLOv8n model, SAFE-YOLO improves PmA@0.5:0.95 by 3.8 percentage points, increases detection speed v by 25.3%, and reduces model parameters M and floating-point operations G by 21.4% and 26.5%, respectively.

Throughout this article, I use the term casting defect repeatedly because the central task is not generic object detection but casting defect detection under industrial edge constraints. The model is evaluated on a custom dataset of surface defects from electric-vehicle front-fork castings. The dataset includes multiple casting defect categories and is designed to reflect real production conditions, including complex backgrounds, metallic reflections, dense sand textures, and oil stains. My goal is to show that a carefully designed lightweight detector can achieve high accuracy for casting defect detection without requiring expensive edge hardware.

Industrial Background and Casting Defect Categories

Casting refers to metal parts manufactured through various casting processes. Traditional casting, also known as liquid forming, involves pouring liquid metal into a mold and allowing it to cool and solidify. To meet precision requirements, special casting technologies such as metal mold casting, pressure casting, and vacuum suction casting are often used. The complexity and diversity of casting processes make casting defects difficult to avoid. Common casting defects include cracks, porosity, shrinkage cavities, sand holes, excess material, and inclusion or abnormal structure. These casting defects can have serious consequences for downstream processing and service performance.

I classify the casting defect types considered in this work according to common industrial naming and classification standards. The dataset contains four main categories: excess material, porosity, crack, and inclusion or abnormal structure. Each category has distinct visual characteristics and different levels of difficulty for casting defect detection. For example, cracks may be elongated, irregular, and low-contrast, while porosity may appear as small dark regions with fuzzy boundaries. Excess material often appears as protrusions or irregular bulges, and inclusion or abnormal structure may appear as local texture anomalies. Table 1 summarizes these casting defect categories and their visual properties.

Casting Defect Category Typical Visual Appearance Detection Difficulty Risk to Downstream Processing
Excess material Protrusions, bulges, irregular added metal Moderate Dimensional deviation, assembly interference
Porosity Small dark holes, fuzzy edges, low contrast High Reduced fatigue strength, leakage paths
Crack Thin, elongated, irregular lines Very high Structural failure, fracture initiation
Inclusion or abnormal structure Local texture anomaly, foreign phase, color difference High Stress concentration, machining damage

The challenge of casting defect detection is not only about recognizing these categories. It is also about detecting them under real imaging conditions. Casting surfaces often have metallic reflections, dense sand grain textures, and oil stains. These factors can confuse a detector and cause false positives or missed detections. Small casting defects occupy only a few pixels, so traditional downsampling can erase them before the detection head sees them. Therefore, a practical model for casting defect detection must preserve fine spatial information while remaining lightweight enough for edge deployment.

Problem Formulation and Edge Deployment Constraints

I formulate casting defect detection as an object detection problem. Given an input image \(I\), the model predicts a set of bounding boxes \(B = \{b_1, b_2, \ldots, b_n\}\), class labels \(C = \{c_1, c_2, \ldots, c_n\}\), and confidence scores \(S = \{s_1, s_2, \ldots, s_n\}\). Each bounding box \(b_i\) is represented by its center coordinates, width, and height. The objective is to maximize detection accuracy while minimizing model size and computational cost. For edge deployment, the model must satisfy constraints on parameters \(M\), floating-point operations \(G\), and inference speed \(v\).

I define the edge deployment condition as follows. The model should have a small parameter count, low computational complexity, and high frames per second. It should also maintain high precision and recall for small casting defects. These requirements are often in conflict. A heavier model may achieve higher accuracy but cannot run on an edge device. A lighter model may run quickly but miss small casting defects. Therefore, I design SAFE-YOLO to achieve a Pareto-optimal balance among accuracy, speed, and model size.

The baseline model I use is YOLOv8n. YOLOv8n is a compact one-stage detector with a backbone, neck, and prediction head. Although it is relatively lightweight, it still has redundancy and may lose fine details during downsampling. I improve it in four ways: SlimNeck for the neck network, SimAM attention at backbone-neck connections, SPDConv for feature re-extraction, and Wise-IoUv3 for loss optimization. These four improvements are complementary and together form the SAFE-YOLO model.

Overall Architecture of SAFE-YOLO

The SAFE-YOLO model contains three main components: the backbone network, the neck network, and the prediction head. The backbone extracts multi-scale features from the input image. The neck fuses features from different scales. The prediction head produces bounding boxes and class probabilities. I keep the general one-stage detection paradigm but replace several components to improve casting defect detection on edge devices.

First, I replace the original neck network with a SlimNeck structure based on GSConv and VoV-GSCSP. This reduces redundant information and improves inference speed. Second, I add SimAM attention at the three connection layers between the backbone and the neck. SimAM is a parameter-free attention mechanism, so it improves feature extraction without increasing computational cost. Third, I replace some standard CBS modules with SPDConv modules. SPDConv uses space-to-depth transformation to avoid information loss during downsampling. This is especially important for small casting defects such as porosity and micro-cracks. Fourth, I replace the CIoU loss with Wise-IoUv3 to accelerate convergence and improve bounding-box regression for irregular casting defects.

Component Baseline Choice SAFE-YOLO Choice Primary Benefit for Casting Defect Detection
Neck network PAN-FPN with C2f SlimNeck with GSConv and VoV-GSCSP Reduced redundancy, faster inference, lower computation
Attention None SimAM at backbone-neck connections Better focus on complex casting defect regions without extra parameters
Downsampling Standard CBS SPDConv Preserved spatial resolution, less loss of small casting defect features
Loss function CIoU Wise-IoUv3 Faster convergence and better regression for irregular casting defects

SlimNeck for Lightweight Feature Fusion

In industrial casting defect detection, inference speed is a key performance metric. The baseline YOLOv8n uses an improved PAN-FPN as the neck network. It fuses high-level semantic information from top to bottom and low-level detail information from bottom to top. The C2f module uses cross-layer connections to improve accuracy, but its multi-branch structure can reduce parallelism on GPU and NPU devices. It also introduces many fragmented operators, which cause frequent DMA data transfers and increase inference latency. To improve speed while maintaining accuracy, I introduce SlimNeck, which is composed of GSConv and VoV-GSCSP.

GSConv combines depthwise convolution and channel shuffle to achieve a lightweight design. Its computational complexity is only about 33% of standard convolution, and it effectively reduces redundant information. GSConv fuses the outputs of standard convolution and depthwise convolution, then uses channel shuffle to enhance feature interaction. This design is suitable for casting defect detection because it maintains representational capacity while reducing computation. VoV-GSCSP is an efficient cross-stage partial network module designed with a one-time aggregation strategy. It reduces the parameter count by about 40% while maintaining good feature extraction ability. By replacing CBS with GSConv and C2f with VoV-GSCSP, I reduce redundant and repeated information without explicit compression, shortening inference time while preserving model accuracy.

I use GSConv in the neck to reduce redundant information and VoV-GSCSP to pass deep semantic features from top to bottom. This reduces parameters and computational burden. The resulting SlimNeck is lighter than the original PAN-FPN and more suitable for edge deployment. The improvement is especially valuable for casting defect detection because the model must run continuously on production lines, where latency accumulates quickly. A faster neck directly increases the number of inspected castings per second.

Module Operation Parameter Impact Computational Impact Role in Casting Defect Detection
GSConv Standard convolution + depthwise convolution + channel shuffle Lower than standard convolution About 33% of standard convolution Reduces redundancy while preserving feature interaction
VoV-GSCSP One-time aggregation cross-stage partial network About 40% reduction Lower than C2f Maintains feature extraction with fewer parameters
SlimNeck GSConv + VoV-GSCSP neck Significantly reduced Significantly reduced Improves inference speed for real-time casting defect detection

To quantify the benefit, I define the computational cost of standard convolution as:

$$C_{std} = k^2 \cdot C_{in} \cdot C_{out} \cdot H \cdot W$$

where \(k\) is the kernel size, \(C_{in}\) is the number of input channels, \(C_{out}\) is the number of output channels, and \(H\) and \(W\) are the spatial dimensions. For depthwise convolution, the cost is:

$$C_{dw} = k^2 \cdot C_{in} \cdot H \cdot W$$

GSConv combines standard convolution and depthwise convolution. Its approximate cost can be expressed as:

$$C_{gs} \approx C_{dw} + \frac{1}{2} C_{std}$$

This formulation explains why GSConv is much cheaper than standard convolution while still preserving useful feature interactions. In casting defect detection, this efficiency allows the model to process more frames per second without dropping small defects.

SimAM Attention for Complex Casting Defect Backgrounds

SimAM is a parameter-free lightweight attention mechanism based on neuroscience theory. It computes an energy function for each neuron and uses the result to generate attention weights. Unlike CBAM and SE, SimAM does not introduce additional parameters, so it improves model performance while maintaining stable inference speed. This property is important for edge deployment because additional parameters and memory access can quickly become bottlenecks.

The energy function of SimAM is defined as:

$$e_{ij} = \frac{4(\mu^2 + \sigma^2)}{(x_{ij} – \mu)^2 + 2\sigma^2 + \varepsilon}$$

where \(e_{ij}\) is the energy at position \((i,j)\), \(x_{ij}\) is the pixel value at that position, \(\mu\) is the global mean of the feature map, \(\sigma^2\) is the global variance, and \(\varepsilon\) is a small constant to avoid division by zero. SimAM uses statistical methods to compute the deviation of each pixel from global features and generates attention weights without extra parameters. It can directly estimate three-dimensional feature weights and adaptively adjust feature-map weights.

I integrate SimAM at the three connection layers between the backbone and the neck. These connections perform feature concatenation before the neck fuses multi-scale information. By adding SimAM before concatenation, the model can enhance important casting defect features and suppress irrelevant background textures. This is particularly useful for casting defect detection because casting surfaces often contain metallic reflections, dense sand textures, and oil stains. Without attention, these background patterns can dominate the feature response and cause false detections. With SimAM, the model focuses more on local regions that are likely to contain casting defects.

Attention Mechanism Additional Parameters Memory Overhead Suitability for Edge Casting Defect Detection
SE Yes Moderate Useful but increases model size
CBAM Yes Moderate to high Effective but less suitable for very lightweight deployment
SimAM No Very low Highly suitable because it improves focus without extra parameters

The benefit of SimAM is not limited to accuracy. It also improves robustness to environmental variation, lighting differences, and surface reflection. In my experiments, adding SimAM improved PmA@0.5:0.95 without increasing model complexity or reducing inference speed. This confirms that SimAM is an effective component for casting defect detection under complex imaging conditions.

SPDConv for Small Casting Defect Preservation

Small casting defects are a major challenge. Porosity, micro-cracks, and shallow sand holes may occupy only a few pixels. Traditional downsampling reduces spatial resolution and can erase these fine details before the detection head processes them. To address this, I introduce SPDConv, a convolution variant designed for small-object detection. SPDConv replaces traditional downsampling with a space-to-depth transformation, preserving detail information.

SPDConv consists of a space-to-depth (SPD) layer and a \(1 \times 1\) convolution layer. For an input feature map of size \(S \times S \times C_1\), the SPD operation rearranges spatial information into the channel dimension. It produces an intermediate feature map of size \(S/2 \times S/2 \times 4C_1\). This operation is a lossless downsampling method because it moves spatial information into channels rather than discarding it. Then, a \(1 \times 1\) convolution adjusts the channel count from \(4C_1\) to \(C_2\), avoiding channel explosion and matching the subsequent network structure. Unlike traditional convolution downsampling, SPDConv minimizes information loss and preserves fine-grained features that are critical for detecting small casting defects.

The space-to-depth operation can be described as follows. Given an input tensor \(X \in \mathbb{R}^{S \times S \times C_1}\), I split it into four sub-tensors:

$$X_{00} = X[0:S:2, 0:S:2, :]$$

$$X_{01} = X[0:S:2, 1:S:2, :]$$

$$X_{10} = X[1:S:2, 0:S:2, :]$$

$$X_{11} = X[1:S:2, 1:S:2, :]$$

Then I concatenate them along the channel dimension:

$$X_{spd} = \text{Concat}(X_{00}, X_{01}, X_{10}, X_{11})$$

The resulting tensor has spatial size \(S/2 \times S/2\) and channel size \(4C_1\). A \(1 \times 1\) convolution then maps it to \(C_2\) channels:

$$Y = \text{Conv}_{1 \times 1}(X_{spd})$$

This design has a small number of parameters and low computational cost because it only contains \(1 \times 1\) convolutions after the rearrangement. It controls model growth and avoids excessive complexity. For casting defect detection, SPDConv is especially valuable because it retains the spatial resolution of small defects. In my feature-map visualization, SPDConv produces clearer and stronger responses in defect regions than traditional downsampling. This indicates that SPDConv helps the model capture subtle casting defect features such as porosity and micro-cracks.

Downsampling Method Spatial Information Loss Parameter Cost Small Casting Defect Preservation Edge Deployment Suitability
Standard strided convolution High Moderate to high Low Moderate
Max pooling High None Low High speed but poor for small defects
SPDConv Low Low High High

Wise-IoUv3 Loss for Irregular Casting Defect Regression

The baseline YOLOv8n uses CIoU as its bounding-box regression loss. CIoU is an advanced IoU-based loss that combines center distance and aspect ratio. It builds on GIoU and DIoU. The CIoU loss is defined as:

$$L_{CIoU} = L_{IoU} + \frac{\sigma(b_y, b_t)}{W_c^2 + H_c^2} + \alpha V$$

where \(L_{IoU}\) is the IoU loss, \(\sigma(b_y, b_t)\) is the Euclidean distance between the predicted and ground-truth box centers, \(W_c\) and \(H_c\) are the width and height of the smallest enclosing rectangle, and \(\alpha\) is an adaptive weight coefficient. The aspect-ratio difference term \(V\) is defined as:

$$V = \frac{4}{\pi^2} \left( \arctan \frac{W_t}{H_t} – \arctan \frac{W_y}{H_y} \right)^2$$

The IoU loss itself is:

$$L_{IoU} = 1 – \frac{b_y \cap b_t}{b_y \cup b_t}$$

Although CIoU is effective for many objects, it has limitations for irregular casting defects. Cracks are often winding and elongated, porosity regions are irregular, and inclusion boundaries may be fuzzy. CIoU may not fit these shapes well, leading to low localization accuracy and slow convergence. It also has ambiguity in describing relative aspect ratios and does not consider sample balance. Therefore, I introduce Wise-IoU and build Wise-IoUv3 for casting defect detection.

Wise-IoUv1 uses a distance attention mechanism. If the predicted box center is \((x,y)\) and the ground-truth box center is \((x_w,y_w)\), the Wise-IoUv1 loss is:

$$L_{Wise-IoUv1} = L_{IoU} \times \exp \left( \frac{(x – x_w)^2 + (y – y_w)^2}{W_c^2 + H_c^2} \right)$$

To avoid harmful gradients caused by low-quality datasets, I construct Wise-IoUv3 by combining a monotonic focusing coefficient with Wise-IoUv1. The Wise-IoUv3 loss is:

$$L_{Wise-IoUv3} = r L_{Wise-IoUv1}$$

The monotonic focusing coefficient \(r\) is:

$$r = \frac{\beta}{\delta \alpha^{\beta – \delta}}$$

where \(\beta\) is the outlier degree that measures prediction-box quality:

$$\beta = \frac{L^*_{IoU}}{L_{IoU}}$$

In these equations, \(\alpha\) and \(\delta\) are hyperparameters that control the shape of \(r\). A smaller \(\beta\) means the predicted box has poor quality. For low-quality samples, \(r\) is small, so the model reduces their negative impact on the overall loss and gradient update. For high-quality samples, \(r\) is close to 1, so their normal gradient contribution is preserved. This dynamic adjustment allows Wise-IoUv3 to remain flexible and highly generalizable. It accelerates convergence and improves regression accuracy for complex casting defect shapes.

Loss Function Key Mechanism Strength Limitation for Casting Defect Detection
IoU Intersection over union Simple and intuitive No gradient for non-overlapping boxes
GIoU Adds enclosing rectangle penalty Handles non-overlapping boxes Slow convergence for irregular shapes
DIoU Adds center distance penalty Better localization Does not consider aspect ratio
CIoU Adds center distance and aspect ratio Good general performance Weak for irregular casting defects and imbalanced samples
Wise-IoUv3 Dynamic focusing and outlier suppression Fast convergence and robust regression Requires careful hyperparameter selection

Dataset Construction and Augmentation

I use a self-made dataset of surface defect images from electric-vehicle front-fork castings. The dataset follows common industrial classification and naming standards for casting defects. It contains four categories: excess material, porosity, crack, and inclusion or abnormal structure. I split the dataset into training, validation, and test sets at a ratio of 7:2:1. The original images were collected from four different angles using an area-scan camera to enhance neural network robustness. To address uneven distribution of casting defect types in real production, I used a labeling method to adjust the data. I collected and produced 874 original defect images. To improve generalization, I used dynamic data augmentation with mirror flipping, geometric transformation, and color transformation. The final dataset contains 2,148 images with annotations. Bounding boxes tightly fit the outer edge of each casting defect, and the aspect ratio matches the actual shape.

According to COCO dataset standards, defects with a pixel area smaller than \(32 \times 32\) are defined as small-object defects. Samples with obvious metal reflection, dense sand texture, or oil stains are marked as complex-background samples. Table 2 shows the dataset information. The high proportion of small casting defects and complex-background samples makes the dataset suitable for evaluating edge-deployment models.

Casting Defect Category Number of Images Number of Defects Small Defects Small Defect Ratio (%) Complex Background Samples
Excess material 473 496 348 70.2 87
Porosity 526 551 456 82.8 121
Crack 583 594 443 74.6 114
Inclusion or abnormal structure 566 582 395 67.9 96

I applied several augmentation techniques to improve model generalization. Table 3 summarizes the augmentation methods and their parameter ranges.

Augmentation Type Specific Operation Parameter Range Purpose
Mirror flip Vertical or horizontal flip Random Increase pose invariance
Geometric transformation Rotation and translation Rotation ±15°, scaling 0.8–1.2× Improve scale and position robustness
Color transformation Brightness, contrast, saturation ±15% Improve illumination robustness

Experimental Environment and Evaluation Metrics

I conducted experiments using the YOLOv8n codebase released by Ultralytics. The CPU was an 18vCPU AMD EPYC 9754 128-Core Processor, and the GPU was an RTX4090 with 24 GiB memory. The software environment was based on Windows 10, with CUDA 11.3 and PyTorch 1.11.0. The batch size was 16. The optimizer was SGD with adaptive anchors enabled. I used cosine annealing for learning rate decay. The training epochs were 150 for the final model.

The evaluation metrics include mean average precision \(PmA\), precision \(P\), recall \(R\), parameter count \(M\), floating-point operations \(G\), and detection speed \(v\). Parameter count represents spatial complexity, and a smaller value means the model is more suitable for mobile or edge devices. Floating-point operations represent temporal complexity, and a smaller value means faster real-time detection. Detection speed represents frames per second and directly reflects real-time capability for casting defect detection.

Precision and recall are defined as:

$$P = \frac{N_{TP}}{N_{TP} + N_{FP}}$$

$$R = \frac{N_{TP}}{N_{TP} + N_{FN}}$$

where \(N_{TP}\) is the number of true positives, \(N_{FP}\) is the number of false positives, and \(N_{FN}\) is the number of false negatives. The mean average precision is:

$$PmA = \frac{1}{n} \sum_{k=1}^{n} \int_{0}^{1} P(R) \, dR$$

where \(n\) is the number of sample categories. In this work, \(PmA@0.5:0.95\) represents the mean average precision over IoU thresholds from 0.5 to 0.95. Table 4 defines the metrics and their roles in casting defect detection.

Metric Symbol Definition Role in Casting Defect Detection
Precision \(P\) True positives divided by true positives plus false positives Measures false alarm rate
Recall \(R\) True positives divided by true positives plus false negatives Measures missed detection rate
Mean average precision \(PmA\) Average precision across classes and IoU thresholds Overall accuracy for casting defect detection
Parameter count \(M\) Number of trainable parameters Model size and memory footprint
Floating-point operations \(G\) Computational cost in GFLOPs Inference cost and energy consumption
Detection speed \(v\) Frames per second Real-time capability on edge devices

Ablation Study

I conducted an ablation study to verify the effectiveness of each improvement. I compared five models: Model A, which is YOLOv8n; Model B, which adds SlimNeck; Model C, which adds SPDConv; Model D, which adds SimAM; and SAFE-YOLO, which adds Wise-IoUv3. I trained each model for 150 epochs. Table 5 shows the ablation results.

Model P (%) R (%) PmA@0.5:0.95 (%) M (10^6) G (GFLOPs) v (FPS)
A (YOLOv8n) 85.6 83.1 74.4 2.8 8.3 83
B (A + SlimNeck) 85.2 82.9 73.8 1.7 5.6 112
C (B + SPDConv) 87.4 82.5 77.0 2.2 5.9 103
D (C + SimAM) 88.1 84.7 77.8 2.2 6.1 101
SAFE-YOLO (D + Wise-IoUv3) 88.3 85.4 78.2 2.2 6.1 104

The ablation results show a clear logical progression. Model B slightly decreases PmA@0.5:0.95 by 0.6 percentage points compared with Model A, but SlimNeck is a key step for lightweight design. SlimNeck sacrifices some feature-fusion complexity and capacity to achieve extreme lightweight and fast detection. This small performance cost is a necessary investment because it significantly reduces \(M\) and \(G\), freeing computational space for SPDConv and SimAM. Model C improves PmA@0.5:0.95 by 3.2 percentage points over Model B. This indicates that SPDConv effectively solves the problem of small casting defect feature loss caused by traditional downsampling. Model D adds SimAM and improves PmA@0.5:0.95 by 0.8 percentage points over Model C. This shows that SimAM enhances the model’s ability to focus on key casting defect features in complex backgrounds. Because SimAM is parameter-free, model complexity and speed remain almost unchanged. Finally, SAFE-YOLO replaces CIoU with Wise-IoUv3 and improves PmA@0.5:0.95 by 0.4 percentage points over Model D. Recall and speed reach their highest values. This indicates that Wise-IoUv3 improves regression accuracy for irregular casting defect bounding boxes through outlier suppression and monotonic focusing.

Compared with Model A, SAFE-YOLO reduces \(M\) and \(G\) by 21.4% and 26.5%, respectively, increases \(v\) by 25.3%, and improves PmA@0.5:0.95 by 3.8 percentage points. These results validate the effectiveness and synergy of the four improvement strategies. They also show that high accuracy and lightweight design can coexist for casting defect detection.

Comparison with Mainstream Detectors

To further verify the efficiency of SAFE-YOLO, I compared it with mainstream models under the same experimental environment, network configuration, and dataset. The compared models include YOLOv12n, YOLOv7-tiny, YOLOv5n, DETR, Faster R-CNN, and SSD. Table 6 shows the comparison results.

Model P (%) R (%) PmA@0.5:0.95 (%) M (10^6) G (GFLOPs) v (FPS)
YOLOv12n 85.6 83.1 75.8 3.0 7.4 78
YOLOv7-tiny 81.2 76.9 68.8 1.8 3.8 125
YOLOv5n 84.4 81.5 73.5 1.9 4.5 96
DETR 83.1 78.7 72.8 45.7 93.2 43
Faster R-CNN 82.0 77.4 65.4 51.3 176.9 16
SSD 78.6 74.5 68.2 28.5 125.6 56
SAFE-YOLO 88.3 85.4 78.2 2.2 6.1 104

The comparison shows that SAFE-YOLO substantially outperforms two-stage models such as Faster R-CNN and DETR in precision. Its PmA@0.5:0.95 is significantly better than that of YOLOv7-tiny, YOLOv5n, YOLOv12n, and SSD. SAFE-YOLO’s detection speed is slightly lower than that of YOLOv7-tiny, but its PmA@0.5:0.95 is 9.4 percentage points higher. This confirms that SAFE-YOLO achieves an excellent balance among accuracy, speed, and model size for casting defect detection. Compared with other mainstream models, SAFE-YOLO has clear competitive advantages for edge-device deployment in industrial casting defect detection scenarios.

Per-Class Detection Performance

I also evaluated per-class performance to understand how SAFE-YOLO handles different casting defect categories. Table 7 presents the per-class precision, recall, and average precision at IoU 0.5. The results show that porosity and crack remain the most difficult classes because they contain many small and low-contrast casting defects. However, SAFE-YOLO still improves these classes compared with the baseline. Excess material and inclusion or abnormal structure achieve higher scores because their visual patterns are more distinct.

Casting Defect Category P (%) R (%) AP@0.5 (%) Main Challenge
Excess material 90.1 87.6 91.2 Shape variation and overlap with normal surface
Porosity 86.8 83.2 87.5 Small size and low contrast
Crack 85.9 82.7 86.4 Irregular and elongated shape
Inclusion or abnormal structure 89.4 86.1 90.3 Texture confusion with sand and oil stains

The per-class results confirm that casting defect detection benefits from the combination of SPDConv, SimAM, SlimNeck, and Wise-IoUv3. SPDConv helps small porosity and crack features survive downsampling. SimAM helps suppress complex background textures. SlimNeck keeps the model fast enough for real-time inspection. Wise-IoUv3 improves localization for irregular crack shapes. Together, these components increase the recall of hard casting defect categories while keeping precision high.

Visualization and Convergence Analysis

I performed feature-map visualization to verify the advantage of SPDConv in feature extraction. Compared with traditional downsampling, SPDConv uses space-to-depth transformation to preserve input information while downsampling. In defect regions, the feature response is clearer and the activation strength is higher, forming a concentrated highlight area. This is important for casting defect detection because small defects can easily disappear in deeper layers. The visualization confirms that SPDConv helps the model retain fine-grained features that are essential for detecting porosity and micro-cracks.

I also compared the convergence performance of Wise-IoUv3 and CIoU during training. The model based on Wise-IoUv3 shows faster convergence speed, a smoother convergence trajectory, and a higher performance plateau. Its training loss curve has a more stable downward trend and smaller fluctuations. This is due to the dynamic focusing mechanism of Wise-IoUv3, which suppresses harmful gradients from low-quality samples. The training process is therefore more robust and efficient. These results verify that Wise-IoUv3 improves convergence and generalization for casting defect detection.

To visualize the detection effect, I compared SAFE-YOLO with YOLOv8n on defect images. SAFE-YOLO shows higher confidence in its predictions. This is consistent with the quantitative results. The improvement is especially visible for small casting defects and complex backgrounds, where the baseline model sometimes produces weak or missing detections. SAFE-YOLO maintains stronger responses and more accurate bounding boxes.

Discussion on Edge Deployment Suitability

Edge deployment requires more than high accuracy. It requires a model that can run on limited hardware without excessive latency, memory usage, or power consumption. SAFE-YOLO is designed with this constraint in mind. The parameter count is only 2.2 million, and the computational cost is 6.1 GFLOPs. The detection speed reaches 104 FPS. These values make SAFE-YOLO suitable for industrial edge devices that must perform casting defect detection in real time.

The model also balances precision and recall. Precision is 88.3%, and recall is 85.4%. High precision means fewer false alarms, which is important because false alarms can cause unnecessary production interruptions. High recall means fewer missed casting defects, which is critical because missed cracks or porosity can lead to safety risks. The improvement in PmA@0.5:0.95 from 74.4% to 78.2% shows that SAFE-YOLO is more accurate across a range of IoU thresholds. This is especially important for irregular casting defects where tight localization is difficult.

Deployment Factor Requirement SAFE-YOLO Performance Implication for Casting Defect Detection
Model size Small enough for edge memory 2.2 million parameters Easy to store and load on edge devices
Computation Low GFLOPs for real-time inference 6.1 GFLOPs Reduced energy consumption and latency
Speed At least 30 FPS for production lines 104 FPS Supports high-throughput casting defect detection
Accuracy High PmA for small and irregular defects 78.2% PmA@0.5:0.95 Reliable detection of cracks, porosity, and inclusions
Robustness Resistance to reflections, sand, and oil stains SimAM and SPDConv improve focus and detail preservation Fewer false positives in complex industrial scenes

I believe SAFE-YOLO is well suited for edge deployment because it does not rely on heavy two-stage detection or large transformer backbones. It uses a compact one-stage architecture with targeted improvements. The SlimNeck reduces redundancy, SimAM improves attention without parameters, SPDConv preserves small casting defect features, and Wise-IoUv3 accelerates convergence. These choices are all aligned with the practical requirements of industrial casting defect detection.

Limitations and Future Work

Despite the strong performance of SAFE-YOLO, some limitations remain. First, the dataset is focused on electric-vehicle front-fork castings. Although it includes multiple casting defect categories and complex backgrounds, other casting geometries and materials may introduce different defect patterns. Future work should evaluate SAFE-YOLO on a wider range of casting defect datasets. Second, the hyperparameters of Wise-IoUv3 require careful selection. Although the dynamic focusing mechanism improves robustness, the values of \(\alpha\) and \(\delta\) may need tuning for different datasets. Third, the model is optimized for 2D images. In some industrial scenarios, 3D surface information or multi-modal sensing could further improve casting defect detection. I plan to explore lightweight multi-modal fusion in future work.

Another direction is quantization and pruning. SAFE-YOLO is already lightweight, but further compression may enable deployment on even smaller devices. I am interested in combining SAFE-YOLO with post-training quantization and structured pruning while preserving accuracy for small casting defects. I also plan to test the model on embedded GPUs and neural processing units to measure real-world latency and power consumption. These steps will help transition SAFE-YOLO from an experimental model to a practical tool for casting defect detection.

Conclusion

I have presented SAFE-YOLO, a lightweight and high-precision model for casting defect detection on edge devices. The model addresses the problems of low detection accuracy for small casting defects, high computational complexity, and slow inference speed in existing detection algorithms. I improved YOLOv8n with four key strategies: SlimNeck for the neck network, SimAM attention at backbone-neck connections, SPDConv for feature re-extraction, and Wise-IoUv3 for loss optimization. Experiments on a custom casting defect dataset show that SAFE-YOLO improves PmA@0.5:0.95 by 3.8 percentage points over YOLOv8n, increases detection speed by 25.3%, and reduces parameters and floating-point operations by 21.4% and 26.5%, respectively. The model achieves a strong balance among accuracy, speed, and model size, making it suitable for industrial edge deployment. The results indicate that SAFE-YOLO can improve the stability of casting defect detection in complex backgrounds, reduce missed and false detections, and provide a practical solution for lightweight real-time casting defect detection. I conclude that SAFE-YOLO has good application prospects and engineering value for casting defect detection in modern manufacturing.

Scroll to Top