I treat casting defect detection as an integrated algorithmic discipline rather than a single classification problem. In my view, a casting defect is not only a local anomaly in an image, a voxel field, or a process record; it is also a physical discontinuity whose morphology, location, scale, and frequency jointly determine the service reliability of a casting. Therefore, I organize the field around five coupled task families: recognition and classification, localization and detection, segmentation and quantitative evaluation, prediction, and image generation for data augmentation. I use the term casting defect repeatedly because the central difficulty is always the same: the casting defect must be separated from noise, texture, structure, process variation, and imbalanced data while remaining physically meaningful.
The industrial motivation is straightforward. Castings are used in aerospace, rail transit, automotive, energy, and general machinery. A casting defect such as a gas pore, shrinkage cavity, shrinkage porosity, crack, inclusion, cold shut, sand hole, or segregation can reduce fatigue life, load-bearing capacity, airtightness, and safety margin. I therefore do not regard detection as a purely visual task. I regard casting defect detection as a chain from signal acquisition to defect representation, defect localization, defect quantification, defect prediction, and finally process feedback. The algorithmic problem is hard because casting defect features are often weak, multi-scale, rare, and entangled with complex backgrounds.
Keywords: casting defect; intelligent inspection; defect recognition; machine vision; deep learning; X-ray imaging; computed tomography; generative augmentation; process prediction
1. Scope and Task Taxonomy
I begin with a taxonomy because different casting defect tasks have different data modalities, outputs, and error costs. A false negative in a safety-critical casting defect can be far more expensive than a false positive, while a false positive in a high-throughput line can cause unnecessary rework. This asymmetry shapes algorithm design. Table 1 summarizes the five task families I use throughout this review.
| Task family | Typical data modality | Typical output | Representative algorithmic route | Primary objective |
|---|---|---|---|---|
| Recognition and classification of casting defect | Visible-light images, X-ray images, CT slices, metallographic images | Defect class label | CNN, ResNet, SVM, ensemble learning | Identify whether a casting defect exists and which class it belongs to |
| Localization and detection of casting defect | X-ray images, industrial images, CT slices | Bounding box, class, confidence | Faster R-CNN, YOLO, FPN, DETR | Locate each casting defect in image space |
| Segmentation and quantitative evaluation of casting defect | 2D images, 3D voxel data, metallographic images | Pixel mask, voxel mask, area, volume, shape descriptors | Mask R-CNN, U-Net, DeepLabV3+, 3D CNN | Extract precise geometry of a casting defect for grading |
| Prediction of casting defect | Process parameters, simulation data, multi-source industrial records | Defect probability, defect volume, quality parameter | ANN, random forest, data-physics fusion | Predict casting defect risk and optimize process settings |
| Generation and augmentation for casting defect | Real images, synthetic images, multimodal data | Synthetic training samples | GAN, diffusion, SMOTE, physical simulation | Mitigate scarcity and imbalance of casting defect samples |
I use the following notation. Let \(x\) be an input image or voxel field, \(y\) the label, and \(f_{\theta}\) a model with parameters \(\theta\). A casting defect detector may output a set \(\{(b_i, c_i, s_i)\}_{i=1}^{N}\), where \(b_i\) is a bounding box, \(c_i\) is a class, and \(s_i\) is a confidence score. A casting defect segmenter outputs a mask \(m \in \{0,1\}^{H \times W}\) or \(m \in \{0,1\}^{D \times H \times W}\). A casting defect predictor outputs a probability \(\hat{p}\) or a continuous quality variable \(\hat{q}\). This notation allows me to compare methods without depending on any particular implementation.
2. Recognition and Classification of Casting Defect
Recognition and classification is the first stage in most casting defect pipelines. I define it as assigning one or more labels to a sample, a region, or a slice. The labels may be binary, such as defective versus non-defective, or multi-class, such as pore, crack, inclusion, shrinkage, cold shut, and sand hole. The central question is how to represent a casting defect when its visual evidence is weak.
2.1 Traditional feature engineering for casting defect classification
Early methods rely on handcrafted features and controlled imaging. I group them into edge-based, region-based, texture-based, and morphology-based families. A typical pipeline applies denoising, contrast enhancement, edge detection, thresholding, connected-component analysis, and feature extraction. Features may include area, perimeter, compactness, elongation, circularity, gray-level mean, gray-level variance, entropy, and local binary patterns. A classifier such as a neural network, SVM, or decision tree then maps the feature vector to a casting defect class.
The advantage of this route is interpretability. I can explain why a region was classified as a casting defect by referring to its area, contrast, and shape. The disadvantage is fragility. If illumination, surface oil, oxidation, or imaging geometry changes, the manually selected thresholds may fail. In my assessment, handcrafted features remain useful for stable, controlled, and high-contrast casting defect inspection, but they are not sufficient for complex internal casting defects with weak boundaries.
Common classification metrics are defined as follows:
$$ \text{Accuracy} = \frac{TP + TN}{TP + TN + FP + FN} $$
$$ \text{Precision} = \frac{TP}{TP + FP} $$
$$ \text{Recall} = \frac{TP}{TP + FN} $$
$$ F_{1} = \frac{2 \cdot \text{Precision} \cdot \text{Recall}}{\text{Precision} + \text{Recall}} $$
For a casting defect with a low occurrence rate, accuracy alone can be misleading. I prefer to report recall and precision together, and I also examine the area under the precision-recall curve when the positive class is rare.
2.2 Feature fusion and ensemble learning for casting defect recognition
When the background is complex, a single feature family rarely captures the full casting defect signature. I therefore view feature fusion as a way to increase the separability between casting defect and background. Texture features describe local roughness, gray-level features describe attenuation or reflectance, and geometric features describe shape. Feature selection methods such as Relief, PCA, or wrapper selection remove redundant dimensions. Ensemble classifiers such as AdaBoost with SVM or random forest combine weak decisions into a stronger boundary.
I summarize the logic as a two-stage problem:
$$ z = \phi(x), \quad \hat{y} = g(z) $$
where \(\phi\) extracts and selects features, and \(g\) is the classifier. The casting defect decision depends on whether \(\phi\) preserves discriminative information. If \(\phi\) collapses different casting defect types into similar feature vectors, no classifier can recover the lost information. This is why I argue that feature representation is the first constraint in casting defect recognition.
| Classification route | Core idea | Strength | Limitation | Suitable casting defect scenario |
|---|---|---|---|---|
| Handcrafted feature + shallow classifier | Extract geometric, gray, texture features; classify with SVM or neural network | Interpretable, low computation | Sensitive to thresholds, illumination, surface contamination | Stable imaging, high-contrast surface casting defect |
| Multi-feature fusion + feature selection | Fuse texture, gray, shape; reduce dimension; ensemble classification | More robust to background variation | Limited feature expressiveness | Internal crack, inclusion, pore classification with moderate data |
| CNN end-to-end | Learn hierarchical features directly from images | Strong representation, less manual design | Needs labeled data, less interpretable | Complex casting defect with variable morphology |
| Attention-enhanced CNN | Focus on discriminative regions and channels | Suppresses background, highlights weak casting defect | Higher complexity, possible overfitting | Low-contrast X-ray or DR images |
| Lightweight CNN | Depthwise separable convolution, mobile backbone, attention | Fast inference, deployable at edge | May lose small casting defect detail | Online production line inspection |
2.3 Deep representation learning for casting defect classification
Convolutional neural networks changed the field because they learn filters directly from data. A convolution layer can be written as:
$$ y_{i,j,k} = \sigma\left(\sum_{c=1}^{C}\sum_{u=-a}^{a}\sum_{v=-b}^{b} w_{u,v,c,k} x_{i+u,j+v,c} + b_k\right) $$
where \(x\) is the input tensor, \(w\) is the kernel, \(b\) is the bias, and \(\sigma\) is a nonlinear activation. Stacking such layers produces features that range from edges to textures to semantic parts. For casting defect classification, this means the model can learn the difference between a pore, a shrinkage cavity, and an inclusion without explicit rules.
I observe three recurring improvements. First, deeper or densely connected backbones improve representation. Second, attention modules reweight channels and spatial locations so that casting defect regions receive more capacity. Third, loss functions are modified to handle hard samples and class imbalance. A typical weighted cross-entropy loss is:
$$ L = -\sum_{i=1}^{N}\sum_{c=1}^{C} \alpha_c y_{i,c} \log \hat{y}_{i,c} $$
where \(\alpha_c\) compensates for the frequency of class \(c\). For casting defect recognition, \(\alpha_c\) is often larger for rare or severe classes. I find this simple adjustment effective when the dataset contains many non-defective samples and few casting defect samples.
2.4 Lightweight and deployable casting defect classifiers
Industrial deployment imposes constraints that are different from benchmark accuracy. A casting defect classifier must often run within a fixed cycle time, on an embedded device, with limited memory and power. I therefore distinguish between laboratory accuracy and line-side feasibility. Techniques such as depthwise separable convolution, channel shuffling, model pruning, knowledge distillation, and quantization reduce computational cost.
The computational cost of a convolution layer can be approximated as:
$$ \text{FLOPs} \approx 2 H W C_{\text{in}} C_{\text{out}} k^2 $$
where \(H\) and \(W\) are spatial dimensions, \(C_{\text{in}}\) and \(C_{\text{out}}\) are channel counts, and \(k\) is the kernel size. Depthwise separable convolution reduces this cost by separating spatial filtering from channel mixing. I consider this important because many casting defect inspection systems must process high-resolution images, and a small reduction in per-pixel cost becomes significant at line speed.
3. Localization and Detection of Casting Defect
Localization answers where a casting defect is. I treat localization as a higher-risk task than classification because a missed casting defect region can escape downstream grading. The output is usually a bounding box with class and confidence. The core evaluation metric is intersection over union:
$$ \text{IoU} = \frac{\text{Area}(B_{\text{pred}} \cap B_{\text{gt}})}{\text{Area}(B_{\text{pred}} \cup B_{\text{gt}})} $$
Average precision is computed by integrating precision over recall:
$$ AP = \int_{0}^{1} p(r) \, dr $$
and mean average precision is the mean of AP over classes:
$$ mAP = \frac{1}{C}\sum_{c=1}^{C} AP_c $$
For casting defect detection, I often report \(mAP@0.5\) and \(mAP@0.5:0.95\). The latter is stricter and better reflects localization quality.
3.1 Pre-deep-learning localization of casting defect
Before deep learning became dominant, casting defect localization relied on image registration, background subtraction, filtering, thresholding, and morphological reconstruction. A common idea is to compare a test image with a defect-free reference. If the reference is accurate, the residual reveals the casting defect. The residual can be written as:
$$ R(x,y) = |I_{\text{test}}(x,y) – I_{\text{ref}}(x,y)| $$
Then a threshold \(T\) yields a binary casting defect candidate map:
$$ M(x,y) = \begin{cases} 1, & R(x,y) \gt T \\ 0, & R(x,y) \le T \end{cases} $$
This approach is computationally efficient, but it depends strongly on registration accuracy and reference quality. Structural edges, machining marks, and casting geometry can create false residuals. I therefore regard it as suitable for fixed-geometry, high-contrast, and well-controlled casting defect inspection.
3.2 CNN-based casting defect detection
Two-stage detectors first generate region proposals and then classify and refine them. Faster R-CNN with a feature pyramid network is a representative route. The feature pyramid combines high-level semantics with low-level detail:
$$ P_l = \text{Conv}(C_l + \text{Upsample}(P_{l+1})) $$
where \(C_l\) is the backbone feature at level \(l\), and \(P_l\) is the pyramid feature. This is important for casting defect detection because a casting defect may appear as a tiny gas pore or as a large shrinkage cavity. Multi-scale fusion improves the representation of both.
One-stage detectors skip region proposals and predict boxes directly. YOLO-family models are common because they provide a favorable speed-accuracy trade-off. A generic detection loss combines classification, localization, and objectness:
$$ L = \lambda_{\text{cls}} L_{\text{cls}} + \lambda_{\text{box}} L_{\text{box}} + \lambda_{\text{obj}} L_{\text{obj}} $$
For casting defect detection, \(L_{\text{box}}\) may use CIoU, EIoU, SIoU, or a Wasserstein-based distance. These losses change how the model penalizes small box errors, which matters for small casting defect targets.

Complex castings such as engine cylinder blocks illustrate why localization is difficult. The geometry contains ribs, bores, channels, and thickness changes. In X-ray or CT views, these structures create overlapping edges and gray-level gradients. A casting defect may be only a few pixels wide, while the background contains strong structural texture. I therefore find that a detector must combine multi-scale feature fusion, attention, and robust box regression to work reliably on such parts.
| Localization family | Representative mechanism | Strength for casting defect | Weakness | Typical use |
|---|---|---|---|---|
| Registration and subtraction | Align test image to reference; threshold residual | Fast, interpretable | Requires accurate reference and registration | Fixed-geometry castings |
| Filtering and thresholding | Butterworth, unsharp masking, iterative threshold | Low computation | Sensitive to parameter choice | High-contrast defect candidates |
| Two-stage CNN | Region proposal plus classification and regression | High accuracy, good for complex backgrounds | Slower inference | High-precision offline analysis |
| One-stage CNN | Dense prediction on feature maps | Fast, suitable for online inspection | Small casting defect may be missed | Production line screening |
| Transformer detector | Self-attention and set prediction | Global context, no anchor design | Data and compute hungry | Complex morphology, high-precision analysis |
3.3 Transformer and attention-based casting defect detection
Transformer detectors model global dependencies through self-attention:
$$ \text{Attention}(Q,K,V) = \text{softmax}\left(\frac{QK^{T}}{\sqrt{d_k}}\right)V $$
For casting defect detection, the advantage is that distant image regions can influence each other. A crack may be long and thin, a shrinkage network may be branched, and an inclusion may be embedded in a textured matrix. Global attention can capture such relationships better than a local convolution alone. However, I also note that Transformer models often require more labeled data and more computation. In industrial casting defect inspection, this trade-off must be evaluated against line speed and hardware cost.
4. Segmentation and Quantitative Evaluation of Casting Defect
Segmentation moves from detection to measurement. I define casting defect segmentation as assigning a pixel or voxel label to each location. The output supports area, perimeter, volume, sphericity, elongation, connectivity, and spatial distribution. These quantities are closer to the physical meaning of a casting defect than a bounding box.
4.1 Traditional segmentation of casting defect
Traditional segmentation combines denoising, contrast enhancement, thresholding, edge detection, and morphology. Otsu thresholding selects a threshold by maximizing between-class variance:
$$ \sigma_b^2(T) = \omega_0(T)\omega_1(T)\left[\mu_0(T) – \mu_1(T)\right]^2 $$
where \(\omega_0\) and \(\omega_1\) are class probabilities, and \(\mu_0\) and \(\mu_1\) are class means. For casting defect images with uneven background, global Otsu may fail. Adaptive thresholding or attribute histograms can improve results by incorporating local or prior information. Morphological reconstruction can then restore the full casting defect region after thresholding.
4.2 Deep segmentation of casting defect
Instance segmentation and semantic segmentation are now common for casting defect analysis. Mask R-CNN extends Faster R-CNN with a mask branch, producing an instance mask for each casting defect. U-Net and DeepLabV3+ use encoder-decoder structures with skip connections or atrous convolution. A generic segmentation loss is:
$$ L_{\text{seg}} = -\frac{1}{N}\sum_{i=1}^{N}\left[y_i \log \hat{y}_i + (1-y_i)\log(1-\hat{y}_i)\right] $$
For imbalanced casting defect segmentation, I often see Dice loss or a combination of Dice and cross-entropy:
$$ L_{\text{Dice}} = 1 – \frac{2\sum_i y_i \hat{y}_i}{\sum_i y_i + \sum_i \hat{y}_i} $$
Dice similarity is also used as a metric:
$$ \text{Dice} = \frac{2|M_{\text{pred}} \cap M_{\text{gt}}|}{|M_{\text{pred}}| + |M_{\text{gt}}|} $$
and the Jaccard index is:
$$ \text{Jaccard} = \frac{|M_{\text{pred}} \cap M_{\text{gt}}|}{|M_{\text{pred}} \cup M_{\text{gt}}|} $$
I find that attention mechanisms and multi-scale context modules are especially useful for casting defect segmentation because they preserve thin boundaries and suppress background texture. Mixed losses also help when the casting defect occupies a very small fraction of the image.
4.3 Three-dimensional segmentation and quantitative evaluation
For internal casting defects, two-dimensional parameters are insufficient. A pore may appear small in one slice but large in three dimensions. A shrinkage network may be connected across slices. A crack may be planar and tortuous. I therefore view 3D segmentation as necessary for high-value castings. A 3D convolution is:
$$ y_{i,j,k,o} = \sigma\left(\sum_{c=1}^{C}\sum_{u,v,w} w_{u,v,w,c,o} x_{i+u,j+v,k+w,c} + b_o\right) $$
After segmentation, quantitative descriptors can be computed. For a casting defect region \(V\), volume is:
$$ V_{\text{defect}} = \sum_{(i,j,k)\in M} v_{\text{voxel}} $$
Surface area can be estimated from the marching cubes mesh or from voxel face counts. Sphericity is:
$$ \Psi = \frac{\pi^{1/3}(6V)^{2/3}}{A} $$
where \(A\) is surface area. Elongation can be derived from principal component analysis of the voxel coordinates. Connectivity can be measured by the number of connected components or by graph-based topological descriptors. These quantities allow a casting defect to be linked to mechanical performance and quality grade.
| Segmentation route | Input | Output | Strength | Limitation |
|---|---|---|---|---|
| Threshold plus morphology | 2D X-ray or DR image | Binary mask | Fast, interpretable | Poor on low-contrast or uneven background |
| Attribute histogram and fuzzy entropy | 2D image | Binary mask | Handles background interference | Requires prior tuning |
| Mask R-CNN | 2D image | Instance mask and class | Instance-level casting defect extraction | Needs pixel-level labels |
| U-Net or DeepLabV3+ | 2D image | Semantic mask | Strong multi-scale context | Class imbalance and thin boundaries remain hard |
| 3D CNN | CT or voxel data | 3D mask | True volumetric measurement | High annotation and computation cost |
4.4 From segmentation to casting defect grading
Quantitative evaluation connects segmentation to standards and engineering decisions. I see three levels. The first is geometric: area, perimeter, volume, and shape. The second is statistical: number, density, size distribution, and spatial clustering. The third is mechanical: stress concentration, fatigue initiation risk, and leakage risk. A simple linear size measure can be defined as:
$$ s = \sqrt{\frac{4A}{\pi}} $$
for an equivalent circular diameter, or:
$$ d_{\text{eq}} = \left(\frac{6V}{\pi}\right)^{1/3} $$
for an equivalent spherical diameter. These equivalent measures are convenient but lossy. I argue that a casting defect grading system should preserve shape and connectivity information, especially for cracks and clustered porosity.
5. Prediction of Casting Defect
Prediction is different from inspection. Instead of asking whether a casting defect is visible, I ask whether a casting defect is likely to form under a given process condition. Inputs may include pouring temperature, mold temperature, shell temperature, pouring time, chemical composition, sand properties, cooling rate, and simulation fields. Outputs may be defect probability, defect class, defect count, defect volume, or a quality score.
5.1 Early neural and expert systems for casting defect prediction
Early work used BP neural networks and expert systems. A BP network computes a weighted sum and activation:
$$ a_j = \sigma\left(\sum_i w_{ij} x_i + b_j\right) $$
and updates weights by gradient descent:
$$ w_{ij} \leftarrow w_{ij} – \eta \frac{\partial L}{\partial w_{ij}} $$
Such models can map process parameters to casting defect probabilities. However, they are black boxes and often cannot explain where or why a casting defect forms. Expert systems add rules and physical criteria, but rule maintenance is labor intensive.
5.2 Data-driven casting defect prediction
With accumulated production data, random forest, K-nearest neighbors, SVM, and neural networks have been applied. Random forest aggregates decision trees. For a node split, Gini impurity is:
$$ G = 1 – \sum_{c=1}^{C} p_c^2 $$
where \(p_c\) is the proportion of class \(c\). Feature importance can be estimated from the decrease in impurity. This is useful because it ranks process parameters by their contribution to casting defect risk. However, feature importance does not reveal interactions. Two parameters may jointly cause a casting defect even if neither is individually dominant. I therefore prefer to combine feature importance with interaction analysis or physics-based reasoning.
| Prediction route | Input | Output | Strength | Weakness |
|---|---|---|---|---|
| BP neural network | Process parameters | Casting defect probability | Nonlinear mapping | Black box, limited position explanation |
| Expert system and criteria | Simulation fields and rules | Casting defect location and cause | Physical interpretability | Rule maintenance cost |
| Random forest | High-dimensional process data | Class probability and feature importance | Robust, handles nonlinearity | Weak interaction explanation |
| Data-physics fusion | Simulation plus measured data | Defect count, volume, quality target | Combines mechanism and learning | Requires simulation and calibration |
5.3 Data-physics fusion for casting defect prediction
I consider data-physics fusion a promising direction because it respects both mechanism and data. A general form is:
$$ \hat{y} = h\left(f_{\text{data}}(x), f_{\text{phys}}(z)\right) $$
where \(f_{\text{data}}\) learns from process records, \(f_{\text{phys}}\) encodes simulation or analytical knowledge, and \(h\) combines them. For example, solidification simulation can provide temperature gradient, cooling rate, and hot spot location. A neural network can then map these fields and process variables to casting defect volume. The combined objective may be:
$$ L = L_{\text{data}} + \lambda L_{\text{phys}} + \mu \|\theta\|_2^2 $$
where \(L_{\text{data}}\) fits observations, \(L_{\text{phys}}\) penalizes violations of physical constraints, and \(\lambda\) controls the physical regularization strength. I find this formulation attractive because it can improve generalization when process conditions shift.
6. Generation and Data Augmentation for Casting Defect
Casting defect samples are rare. This is a structural problem, not a temporary data shortage. In a healthy production line, most castings are acceptable, and severe casting defects are even rarer. A model trained on such data will be biased toward the majority class. I therefore treat generation and augmentation as essential components of casting defect detection.
6.1 Physical and geometric simulation of casting defect images
One route is to simulate the imaging process. In X-ray imaging, the Beer-Lambert law relates transmitted intensity to attenuation and path length:
$$ I = I_0 \exp\left(-\int_{L} \mu(s) \, ds\right) $$
If a casting defect changes the local attenuation coefficient or the effective path length, the detector intensity changes. A virtual casting defect image can be generated by modeling the geometry and attenuation. This approach is interpretable and controllable, but it requires accurate models and becomes expensive when the casting defect morphology is complex.
6.2 GAN-based casting defect image synthesis
Generative adversarial networks learn a mapping from noise to images. The original minimax objective is:
$$ \min_G \max_D V(D,G) = \mathbb{E}_{x\sim p_{\text{data}}(x)}[\log D(x)] + \mathbb{E}_{z\sim p_z(z)}[\log(1-D(G(z)))] $$
Wasserstein GAN replaces the Jensen-Shannon divergence with a Wasserstein distance:
$$ \min_G \max_{D\in \mathcal{D}} \mathbb{E}_{x\sim p_{\text{data}}}[D(x)] – \mathbb{E}_{z\sim p_z}[D(G(z))] $$
For casting defect generation, a common strategy is to synthesize a casting defect region and then blend it into a real defect-free background. This preserves background realism while controlling casting defect shape. A blended image can be written as:
$$ I_{\text{syn}} = (1-M)\odot I_{\text{bg}} + M\odot I_{\text{defect}} $$
where \(M\) is a blending mask and \(\odot\) is element-wise multiplication. I find this composite strategy practical because it decouples background appearance from casting defect appearance.
| Generation route | Mechanism | Strength | Limitation |
|---|---|---|---|
| Physical simulation | Model ray attenuation and geometry | Physical plausibility, controllable | High modeling cost |
| Geometric and stochastic simulation | Generate elevation or gray-level fields | Simple, fast | Manual parameters, limited realism |
| GAN and variants | Adversarial learning of defect appearance | Diverse textures, high resolution | Unstable training, evaluation difficulty |
| Diffusion models | Iterative denoising from noise | High sample quality, controllable generation | Slow inference, compute intensive |
| SMOTE and feature-space oversampling | Interpolate minority samples in feature space | Simple, effective for tabular process data | Not directly suitable for images |
6.3 Synthetic sample evaluation for casting defect detection
I argue that synthetic casting defect images should be judged by their effect on downstream detection, not only by visual realism. Useful checks include:
$$ \Delta mAP = mAP_{\text{real+synthetic}} – mAP_{\text{real}} $$
$$ \Delta Recall = Recall_{\text{real+synthetic}} – Recall_{\text{real}} $$
If synthetic casting defect samples improve recall on a held-out real set without increasing false positives excessively, they are useful. If they only improve training accuracy, they may be reinforcing generator bias. I also recommend physical consistency checks: size distribution, shape statistics, gray-level distribution, and spatial distribution should fall within plausible ranges.
7. Common Difficulties and Optimization Paths
Across the five task families, I see four recurring difficulties. They are weak features, small and multi-scale targets, complex background interference, and sample scarcity with class imbalance. These difficulties are not independent. A weak casting defect is often small, rare, and embedded in a complex background. Therefore, I prefer to design a casting defect detection system as a joint optimization problem.
7.1 Weak feature expression for casting defect
Weak features arise when the casting defect contrast is low and the boundary is blurred. The local contrast can be defined as:
$$ C = \frac{|I_{\text{defect}} – I_{\text{background}}|}{I_{\text{background}} + \epsilon} $$
and the signal-to-noise ratio as:
$$ SNR = \frac{\mu_{\text{defect}} – \mu_{\text{background}}}{\sigma_{\text{background}}} $$
If \(C\) or \(SNR\) is low, a detector may confuse the casting defect with noise. I summarize the optimization paths as denoising, contrast enhancement, feature selection, attention, and background suppression. Among these, attention is appealing because it learns where to focus. However, I caution that attention cannot create information that is not present. If the imaging system does not capture the casting defect signal, no algorithm can reliably recover it.
7.2 Small and multi-scale casting defect detection
Small casting defects lose spatial detail after repeated downsampling. If the input resolution is \(H \times W\) and the network stride is \(s\), the feature map resolution is approximately \(H/s \times W/s\). A casting defect of size \(d\) may occupy fewer than one feature cell when \(d \lt s\). This is why small casting defect detection requires high-resolution feature preservation.
Multi-scale fusion can be expressed as:
$$ F_{\text{fused}} = \sum_{l=1}^{L} \alpha_l \text{Resize}(F_l) $$
where \(\alpha_l\) are learned or fixed weights. A small object detection head adds a high-resolution branch. A normalized Wasserstein distance loss can make box regression more tolerant to small position errors:
$$ NWD = \exp\left(-\frac{W_2^2(\mathcal{N}_p, \mathcal{N}_g)}{C}\right) $$
where \(W_2\) is the Wasserstein distance between Gaussian representations of predicted and ground-truth boxes. I find such losses useful when the casting defect is only a few pixels wide.
7.3 Complex background and low-contrast interference
Complex backgrounds contain structural edges, machining marks, surface roughness, and overlapping objects. A casting defect may resemble a legitimate structure. I group countermeasures into three classes. The first is prior knowledge, such as using a 3D model or a defect-free reference. The second is context modeling, such as attention, feature pyramids, and non-local blocks. The third is feature reconstruction, where the model learns the normal background and flags deviations.
A reconstruction-based anomaly score can be written as:
$$ A(x) = \|x – \hat{x}\|_2^2 $$
If the reconstruction error is large, the region is a casting defect candidate. This is attractive when defect samples are scarce, but it can also flag rare but acceptable process variations.
7.4 Sample scarcity and class imbalance for casting defect
Class imbalance affects training and evaluation. A model may achieve high accuracy by predicting the majority class, while missing most casting defect samples. I therefore use class-weighted losses, focal loss, resampling, and synthetic augmentation. Focal loss is:
$$ FL(p_t) = -\alpha_t (1-p_t)^{\gamma} \log(p_t) $$
where \(\gamma\) down-weights easy examples. For tabular process data, SMOTE generates synthetic minority samples by interpolation:
$$ x_{\text{new}} = x_i + \lambda (x_{nn} – x_i), \quad \lambda \in [0,1] $$
where \(x_{nn}\) is a nearest neighbor of the same class. I find SMOTE useful for casting defect prediction from process parameters, but less appropriate for high-dimensional images without feature extraction.
| Common difficulty | Main cause | Typical effect | Optimization path | Representative techniques |
|---|---|---|---|---|
| Weak casting defect features | Low contrast, blurred boundary, noise, structural texture | Missed detection, false alarm, unstable representation | Image enhancement, feature selection, background suppression, attention | Bilateral filtering, adaptive thresholding, Relief selection, self-attention |
| Small and multi-scale casting defect | Low pixel ratio, repeated downsampling, scale variation | Low recall for small defects, large localization error | Shallow feature preservation, multi-scale fusion, small-object head, box loss redesign | FPN, PAN, P2 head, NWD loss, coordinate attention |
| Complex background and low contrast | Structure edges, texture, noise, reflection, occlusion | Defect and background confusion, poor generalization | Prior knowledge, context modeling, attention enhancement, reconstruction | 3D model subtraction, global attention, knowledge distillation |
| Sample scarcity and imbalance | Low defect rate, severe defect rarity | Bias toward majority class, low minority recall | Oversampling, data synthesis, generative augmentation, task-driven evaluation | SMOTE, physical simulation, GAN, diffusion |
8. Evaluation Metrics and Experimental Discipline
I consider evaluation a core part of casting defect algorithm research. A method that reports only accuracy is difficult to interpret. I prefer a metric panel that reflects the cost of missing a casting defect, the cost of false alarms, localization quality, segmentation quality, and calibration. Table 8 summarizes the metrics I use most often.
| Task | Metric | Formula or meaning | Why it matters for casting defect |
|---|---|---|---|
| Classification | Accuracy | \((TP+TN)/(TP+TN+FP+FN)\) | Overall correctness, but can hide rare casting defect failure |
| Classification | Precision | \(TP/(TP+FP)\) | Controls false alarms and unnecessary rework |
| Classification | Recall | \(TP/(TP+FN)\) | Controls missed casting defects |
| Classification | F1 | Harmonic mean of precision and recall | Balanced summary under imbalance |
| Detection | IoU | Intersection over union of boxes | Measures localization accuracy |
| Detection | mAP | Mean average precision over classes | Standard detection comparison |
| Segmentation | Dice | \(2|M_p\cap M_g|/(|M_p|+|M_g|)\) | Measures overlap of casting defect regions |
| Segmentation | Jaccard | \(|M_p\cap M_g|/|M_p\cup M_g|\) | Strict overlap measure |
| Prediction | RMSE | \(\sqrt{\frac{1}{N}\sum_i(y_i-\hat{y}_i)^2}\) | Measures continuous defect volume or quality error |
| Prediction | R2 | \(1-\sum_i(y_i-\hat{y}_i)^2/\sum_i(y_i-\bar{y})^2\) | Measures explained variance of process prediction |
I also recommend reporting per-class results, confidence intervals, and cross-validation under different imaging or process conditions. A casting defect model trained on one machine, one alloy, or one batch may fail on another. Generalization is therefore a first-class experimental question.
9. Future Directions
I see four directions that are likely to shape the next stage of casting defect detection.
9.1 Self-supervised and weakly supervised representation learning
High-quality annotation of casting defect is expensive. Pixel-level labels for a casting defect are especially costly because boundaries are ambiguous. Self-supervised learning can use large amounts of unlabeled images to learn generic representations. A contrastive objective can be written as:
$$ L_{\text{contrast}} = -\log \frac{\exp(\text{sim}(z_i, z_i^+)/\tau)}{\sum_{j}\exp(\text{sim}(z_i, z_j)/\tau)} $$
where \(z_i\) and \(z_i^+\) are different views of the same sample, and \(\tau\) is a temperature. I expect this to reduce dependence on large casting defect annotations.
9.2 Multi-task collaborative modeling for casting defect
Detection, segmentation, grading, and prediction are often treated as separate tasks. I believe they should share representations. A multi-task loss can be:
$$ L_{\text{total}} = \sum_{t=1}^{T} \lambda_t L_t $$
where \(t\) indexes tasks such as classification, localization, segmentation, and quality regression. Shared encoders can learn casting defect features that benefit all tasks. This is especially attractive for high-value castings where the same image must support both inspection and process feedback.
9.3 Generative and multimodal augmentation for casting defect
GANs have shown practical value, but diffusion models and multimodal generative models may offer better controllability. A conditional diffusion process can be described by forward noise addition:
$$ q(x_t|x_{t-1}) = \mathcal{N}\left(x_t; \sqrt{1-\beta_t}x_{t-1}, \beta_t I\right) $$
and a learned reverse process:
$$ p_{\theta}(x_{t-1}|x_t) = \mathcal{N}\left(x_{t-1}; \mu_{\theta}(x_t,t), \Sigma_{\theta}(x_t,t)\right) $$
For casting defect generation, conditioning variables may include defect class, size, location, and process condition. I regard controllable generation as more valuable than unconditional realism.
9.4 Edge deployment and system integration for casting defect inspection
Finally, I emphasize deployment. A casting defect algorithm must be integrated with cameras, X-ray sources, detectors, robots, programmable logic controllers, and quality databases. The end-to-end latency is not only model inference. It includes acquisition, preprocessing, inference, postprocessing, communication, and actuation. I therefore recommend co-design of algorithm, hardware, and compiler. Quantization and pruning can be written as constrained optimization:
$$ \min_{\theta} L(\theta) \quad \text{subject to} \quad \text{FLOPs}(\theta) \le B, \quad \text{Memory}(\theta) \le M $$
where \(B\) and \(M\) are hardware budgets. This formulation captures the real constraint of online casting defect inspection.
10. Conclusion
I have reviewed casting defect detection algorithms as a connected system. Recognition and classification provide the label; localization provides the position; segmentation and quantitative evaluation provide the geometry; prediction provides process foresight; generation provides data support. The strongest trend is the shift from handcrafted rules to learned representations, and then toward data-physics fusion and controllable generative augmentation.
At the same time, I do not think deep learning has removed the fundamental difficulties. The casting defect remains weak, small, rare, and entangled with background. The best-performing methods combine signal enhancement, multi-scale representation, attention, robust loss design, and physically meaningful evaluation. I conclude that future progress in casting defect detection will depend less on a single network architecture and more on integrated design: data acquisition, annotation strategy, model architecture, physical constraints, evaluation metrics, and edge deployment must be optimized together. In that sense, casting defect detection is not only a vision problem; it is a manufacturing intelligence problem in which every casting defect must be detected, measured, explained, and ultimately prevented.
