Machine Learning Methods for Casting Defect Recognition

The quality assurance of cast components has always been a central issue in foundry engineering. In particular, sand foundry defects seriously influence the mechanical performance and service life of aerospace components. In this thesis, I focus on the recognition of sand foundry defects by using X-ray imaging, digital image processing, and machine learning algorithms. The proposed framework consists of image preprocessing, defect segmentation, multi-feature extraction, feature selection, and classification via an ensemble model. I first analyze the causes and morphological properties of common sand foundry defects such as gas pores, shrinkage, crack-like discontinuities, and inclusions. Then I develop a reliable pipeline to enhance the tiny defect structures in X-ray images, extract representative features, and finally classify the defect types using an Adaboost-SVM model. The experiments are carried out on data collected from a real casting production line for aerospace light alloy parts. The results show that the proposed method achieves high accuracy and low false negative rates in identifying multiple sand foundry defects. Moreover, I verify the benefit of the SVM-RFE feature selection strategy and the ensemble classifier in improving the robustness of defect recognition.

Introduction

In modern industry, casting is one of the most economical and efficient methods for manufacturing complex metal parts. However, the casting process inevitably introduces internal discontinuities, which are generally regarded as sand foundry defects. These defects may be caused by inadequate gating systems, poor mold compactness, gas entrapment, shrinkage during solidification, or the inclusion of foreign materials. If such sand foundry defects remain undetected, they can lead to premature failure of the component. This is especially critical in aerospace applications where safety margins are strict. Therefore, reliable non-destructive inspection, followed by accurate defect recognition, is essential to ensure the integrity of cast products.

Among different non-destructive testing techniques, X-ray radiography is widely used because it is capable of revealing internal structures and defects in cast components without damaging the workpiece. The X-ray images, however, often suffer from low contrast, irregular noise, and complex background. Moreover, sand foundry defects have diverse shapes, sizes, locations, and orientations. These characteristics make traditional manual inspection difficult, time-consuming, and subjective. Hence, there is an increasing need for automated recognition frameworks based on machine learning.

In this work, I consider the problem of sand foundry defect recognition in X-ray images of aerospace light alloy castings. The main contributions are summarized as follows: (1) I design a preprocessing pipeline that combines linear gray-level transformation, bilateral filtering, edge detection, and adaptive threshold segmentation to enhance and separate defect regions. (2) I extract a multi-view feature set containing geometric shape descriptors, Hu invariant moments, Local Binary Patterns (LBP), and Histograms of Oriented Gradients (HOG). Because the raw HOG descriptor is high-dimensional, I apply Principal Component Analysis (PCA) for preliminary dimensionality reduction. (3) I use support vector machine recursive feature elimination (SVM-RFE) to select a compact and discriminative feature subset from the fused feature space. (4) I construct an Adaboost-SVM classifier by integrating multiple SVM learners so that the final model is more stable and accurate than a single SVM for the classification of sand foundry defects.

Image Preprocessing and Segmentation

The first step in the automatic recognition of sand foundry defects is to improve the quality of the acquired X-ray image. In the production environment, the X-ray images usually show non-uniform illumination, low contrast, and heavy noise. These factors can severely degrade the performance of the later feature extraction and classification steps. Therefore, I preprocess the images using a linear gray-level transformation, followed by a bilateral filter. Then I segment the defect candidates using edge detection and adaptive threshold segmentation.

Defect Category Analysis

To design an effective recognition algorithm, I first analyze the typical categories of sand foundry defects. The most common defect types in aluminum and magnesium alloy castings are gas pores, shrinkage porosity, hot tears or cracks, and inclusions.

Gas pores usually appear as round or elliptical dark regions with low gray-level values. They are caused by gas bubbles that are trapped in the molten metal during solidification. In an X-ray image, gas pores can be isolated or distributed in clusters, and their boundaries are typically smooth.

Shrinkage porosity is formed when the liquid metal supply is insufficient during solidification. This type of sand foundry defect often has a sponge-like or branched appearance. Under X-ray, shrinkage regions may exhibit a cloud-like dark structure with irregular edges. Shrinkage is frequently found in the thermal center of a thick casting section.

Cracks are generally long and narrow discontinuities with sharp tips. They are often caused by thermal stresses during cooling. In the X-ray image, a crack appears as a fine dark line with significant length and a small width. The orientation of the crack may vary with the stress distribution.

Inclusions are foreign materials that are accidentally mixed into the casting. They may be lighter or darker than the surrounding metal depending on their composition. Inclusions have irregular shapes and can appear anywhere in the casting. Other defect types, such as cold shut, misrun, and sand burn, may also appear in sand foundry defects, but they are less frequent in the case of aerospace castings.

Gray-level Transformation

To enhance the contrast between defect regions and the background, I apply a linear gray-level transformation. Suppose the original image has gray values in the range \([a,b]\). After linear transformation, the values are mapped to a new range \([a’,b’]\). The operation is defined as follows:

$$
f(x,y) = a’ + \frac{b’-a’}{b-a} \bigl( g(x,y) – a \bigr)
$$

where \(g(x,y)\) is the original pixel value at coordinate \((x,y)\), and \(f(x,y)\) is the enhanced pixel value. By stretching the gray-level range, the contrast of the image is improved, which makes the sand foundry defects more visible.

In some cases, the useful gray levels are concentrated in a small interval. Linear gray transformation can also be extended to a piecewise linear operation. In this work, I select a simple linear transformation because it is computationally efficient and adequate for the X-ray images under study.

Image Filtering

Image filtering is applied to suppress noise while preserving the important details of defect boundaries. I compared four common filtering methods: mean filtering, median filtering, Gaussian filtering, and bilateral filtering.

Mean filtering replaces each pixel with the average value in a neighborhood window. For a window size \(n \times n\), the output is

$$
f'(x,y) = \frac{1}{n\times n} \sum_{(i,j)\in W_{x,y}} f(i,j)
$$

Mean filtering is simple but it tends to blur edges, which is unfavorable for the fine structure of cracks and shrinkage.

Median filtering replaces each pixel with the median value of its neighbors. It is effective for removing impulse noise, but it may remove small defect structures and creates artificial discontinuities.

Gaussian filtering uses a Gaussian kernel to compute a weighted average of neighboring pixels. The two-dimensional Gaussian function is

$$
G(x,y,\sigma) = \frac{1}{2\pi\sigma^2} \exp\left( -\frac{x^2+y^2}{2\sigma^2} \right)
$$

Gaussian filtering is isotropic and can suppress Gaussian noise, but it also tends to smooth out weak defect boundaries.

Bilateral filtering is a nonlinear edge-preserving filter. It combines spatial proximity and intensity similarity. The output is computed as

$$
f'(x) = \frac{1}{W_x} \sum_{y \in S_x} G_{\sigma_s}(\|x-y\|) \, G_{\sigma_r}(|I(x)-I(y)|) \, I(y)
$$

where \(S_x\) is a spatial neighborhood around pixel \(x\), \(W_x\) is a normalization factor, \(\sigma_s\) controls the spatial weighting, and \(\sigma_r\) controls the intensity weighting. The bilateral filter can effectively reduce noise while keeping the sharp edges of sand foundry defects. By comparing the experimental results on the casting images, I selected bilateral filtering for this study.

Image Segmentation

After filtering, I apply segmentation methods to separate the defect regions from the background. Two common approaches are edge-based segmentation and threshold-based segmentation.

Edge detection is based on the gray-level discontinuity between defects and their surroundings. The gradient of the image is computed as

$$
\nabla f = \begin{bmatrix} G_x \\ G_y \end{bmatrix}
= \begin{bmatrix} \frac{\partial f}{\partial x} \\ \frac{\partial f}{\partial y} \end{bmatrix}
$$

The magnitude is \(M(x,y) = \sqrt{G_x^2 + G_y^2}\), and the edge direction is \(\theta = \arctan(G_y/G_x)\). I use the Canny edge detector because it provides good localization and is robust to noise. The Canny algorithm includes Gaussian smoothing, gradient computation, non-maximum suppression, and hysteresis thresholding.

For threshold-based segmentation, adaptive thresholding is more suitable than a single global threshold because the background of casting X-ray images is not uniform. Let \(J(x,y)\) be the pixel value after preprocessing. I first compute the mean value \(F(J(x,y))\) over a local window, and then define the threshold as

$$
T(x,y) = (1 – \alpha) \, F(J(x,y))
$$

where \(\alpha\) is a selected ratio. The binary image is obtained by:

$$
J'(x,y) =
\begin{cases}
255, & J(x,y) < T(x,y) \\
0, & J(x,y) \ge T(x,y)
\end{cases}
$$

In this way, dark defect candidates are highlighted. The combination of Canny edge detection and adaptive threshold segmentation provides complementary information for different types of sand foundry defects. For crack-like defects, the edge detector can trace the fine lines; for volumetric defects such as gas pores and shrinkage, the adaptive threshold can extract the entire dark region.

The production process of a casting line is shown in the following image. This image represents the automatic pouring stage in a modern foundry where sand foundry defects are controlled through careful process monitoring.

Feature Extraction and Classifier Design

Once the defect regions are segmented, the next stage is to extract meaningful features that can distinguish different categories of sand foundry defects. Because sand foundry defects vary significantly in shape, size, orientation, and grey-level distribution, a single kind of feature is often insufficient. Therefore, I extract four complementary feature families and then fuse them.

Geometric Shape Features

Geometric features describe the shape and structure of the defect region. I computed the following descriptors: area, perimeter-to-area ratio, aspect ratio, rectangularity, sharpness, and mean gray-level.

The area \(S\) of a defect region is the total number of pixels inside the region. The perimeter is the length of the contour. The aspect ratio is defined as \(A = L/W\), where \(L\) is the length of the minimum bounding rectangle and \(W\) is the width. The rectangularity is \(R = S / S_{\text{rect}}\), where \(S_{\text{rect}}\) is the area of the minimum bounding rectangle. The sharpness \(P\) is defined as the sum of the two end-region areas divided by the total defect area:

$$
P = \frac{S_1 + S_2}{S}
$$

where \(S_1\) and \(S_2\) correspond to the two endpoints of the defect. The mean gray-level is the average intensity inside the defect area. These geometric features are quite intuitive and can separate elongated cracks from round gas pores, as well as irregular shrinkages from compact inclusions.

Hu Moment Features

Hu invariant moments have been widely used for shape analysis because they are invariant to translation, scale, and rotation. For a digital image \(f(x,y)\), the central moment of order \(p+q\) is defined as

$$
\mu_{pq} = \sum_x \sum_y (x-\bar{x})^p (y-\bar{y})^q f(x,y)
$$

where \(\bar{x}\) and \(\bar{y}\) are the centroid coordinates. The normalized central moments are

$$
\eta_{pq} = \frac{\mu_{pq}}{\mu_{00}^{1 + (p+q)/2}}
$$

From these normalized moments, I compute seven Hu invariant moments \(I_1, I_2, \dots, I_7\). They capture global shape information that is not easily reflected by simple geometric parameters. In the context of sand foundry defects, Hu moments help to distinguish the branching structure of shrinkage from the circular shape of gas pores.

LBP Texture Features

Local Binary Pattern (LBP) is an effective texture descriptor that is robust to gray-level changes. The original LBP operator works in a \(3 \times 3\) neighborhood. Each pixel is compared with its center pixel and then encoded as a binary string:

$$
\mathrm{LBP}(x_c,y_c) = \sum_{p=0}^{P-1} s(i_p – i_c) \, 2^p
$$

where \(i_c\) is the gray value of the center pixel, \(i_p\) is the gray value of a neighbor, and \(s(\cdot)\) is a sign function

$$
s(x) = \begin{cases} 1, & x \ge 0 \\ 0, & x < 0 \end{cases}
$$

To improve the operator, I use the extended circular neighborhood and the equivalent pattern mapping. The uniform LBP patterns have at most two bitwise transitions between 0 and 1. This significantly reduces the number of features while preserving the discriminative information. In my method, the LBP image is computed and then the histogram is used as the texture feature for sand foundry defects.

HOG Features and PCA Reduction

Histogram of Oriented Gradients (HOG) is a widely used feature for object detection and shape description. The image is divided into small cells, and the gradient orientation histograms are calculated for each cell. The gradient magnitude and orientation are defined as

$$
G(x,y) = \sqrt{G_x^2 + G_y^2}
$$

$$
\theta(x,y) = \arctan\left( \frac{G_y}{G_x} \right)
$$

where \(G_x\) and \(G_y\) are the horizontal and vertical gradients:

$$
G_x(x,y) = f(x+1,y) – f(x-1,y)
$$

$$
G_y(x,y) = f(x,y+1) – f(x,y-1)
$$

The HOG descriptor is composed of a series of block histograms across the whole image. Although HOG is a powerful descriptor, its dimension is usually very large. To avoid introducing too many redundant features and to reduce the computational burden, I apply Principal Component Analysis (PCA).

PCA identifies an orthogonal set of principal components that maximize the variance in the data. Given a data matrix \(X\), the covariance matrix is

$$
Q = \frac{1}{n} \sum_{i=1}^{n} (x_i – \bar{x})(x_i – \bar{x})^T
$$

The principal components are the eigenvectors of \(Q\) corresponding to the largest eigenvalues. I keep the number of principal components that retain a specified percentage of the total variance, e.g. 99.99%.

SVM-RFE Feature Selection

After extracting features from the four families, I concatenate them into a full feature vector. However, the full feature set may contain redundant or irrelevant information, which reduces the classification performance and increases training time. To solve this problem, I use SVM-RFE for feature selection.

Support Vector Machine (SVM) is a supervised learning model that finds the hyperplane with maximum margin. The primal optimization problem is

$$
\min_{w,b,\xi} \; \frac{1}{2} \|w\|^2 + C \sum_{i=1}^{N} \xi_i
$$

$$
\text{s.t.} \; y_i(w \cdot x_i + b) \ge 1 – \xi_i, \; \xi_i \ge 0
$$

where \(C\) is a penalty parameter and \(\xi_i\) are slack variables. The decision function is

$$
f(x) = \operatorname{sign}\left( \sum_{i=1}^{N} \alpha_i y_i K(x_i, x) + b \right)
$$

SVM-RFE ranks features by the weight \(w_j\) of each feature. The ranking score is computed as

$$
g_j = w_j^2
$$

In each iteration, the feature with the smallest score is removed. Then the SVM is re-trained on the remaining features. This process is repeated until the desired feature subset size is reached. The selected features form the key-sensitive feature set, which should preserve the most relevant information for sand foundry defect classification.

Adaboost-SVM Model Construction

Although SVM has good classification ability, a single SVM may still be unstable when the data set is small and highly complex. To overcome this issue, I adopt the idea of ensemble learning, specifically the Adaboost algorithm. Adaboost trains multiple weak classifiers and combines them into a strong classifier. In the proposed framework, I use SVM as the base classifier and integrate it with Adaboost.

The training procedure of Adaboost-SVM is as follows:

1. Initialize the sample weights \(w_{1,j}=1/d\) for each training sample, where \(d\) is the number of training samples.

2. For iteration \(t = 1, 2, \dots, T\):

Train an SVM classifier \(h_t(x)\) on the weighted training set. Compute the weighted error rate:

$$
e_t = \sum_{j=1}^{d} w_{t,j} \, \mathbb{I}\left( y_j \neq h_t(x_j) \right)
$$

Then compute the classifier weight:

$$
\alpha_t = \frac{1}{2} \ln\left( \frac{1 – e_t}{e_t} \right)
$$

Update the sample weights:

$$
w_{t+1,j} = \frac{w_{t,j}}{B_t} \exp\left( – \alpha_t \, y_j \, h_t(x_j) \right)
$$

where \(B_t\) is a normalization factor that keeps the total weight sum equal to 1.

3. The final strong classifier is

$$
H(x) = \operatorname{sign}\left( \sum_{t=1}^{T} \alpha_t h_t(x) \right)
$$

In this ensemble model, each SVM classifier focuses on the samples that were misclassified by the previous classifiers. This adaptive boosting mechanism improves the overall classification accuracy and generalization of sand foundry defect recognition.

Experimental Verification

To validate the proposed method, I used a real-world dataset from an aerospace light alloy casting production line. The product under study is an aerospace tail cabin casting. The production line includes sand testing, core-making, melting, pouring, shake-out, grinding, rough machining, X-ray inspection, defect repair, heat treatment, and final inspection. In particular, the X-ray inspection step is used to detect sand foundry defects in the casting.

At the beginning of the project, I collected 38 original X-ray images, which included 14 crack images, 14 shrinkage images, and 14 gas pore images, plus 23 defect-free images. Because the original data were limited, I applied data augmentation techniques such as horizontal flipping, vertical flipping, rotation, and adding Gaussian noise. After augmentation, the dataset contained 560 images in total, distributed equally among the four classes.

The table below shows the data distribution after augmentation.

Dataset distribution
Category Original Augmented
Crack 14 112
Gas pore 14 112
Shrinkage 14 112
Defect-free 23 184
Total 65 560

In the preprocessing stage, I used linear gray-level transformation to improve contrast. The bilateral filter parameters were set as follows: spatial window size \(5 \times 5\), \(\sigma_s = 20\), and \(\sigma_r = 0.2\). For edge detection, I used the Canny operator with a low threshold of 50 and a high threshold of 250. For adaptive thresholding, the smoothing window size was \(15 \times 15\), and the ratio was set to 0.15.

After preprocessing and segmentation, I extracted features from each image. The geometric features were six-dimensional. The Hu moments were seven-dimensional. The LBP histogram was computed with a uniform pattern of dimension 59. The HOG descriptor was much larger, so PCA was used to compress it while preserving 99.99% of the variance. Then I concatenated all features into a high-dimensional feature vector. Next, I applied SVM-RFE to select the top 60% of the ranked features as the sensitive feature subset. In order to verify the selected threshold, I compared several selection ratios. The table below lists the comparison results.

Comparison of different feature selection thresholds
Selection ratio Accuracy for crack Accuracy for gas pore Accuracy for shrinkage
10% 0.894 0.891 0.905
20% 0.902 0.908 0.900
30% 0.924 0.905 0.923
40% 0.921 0.913 0.920
50% 0.932 0.918 0.931
60% 0.961 0.921 0.943
70% 0.942 0.915 0.934
80% 0.931 0.906 0.921
90% 0.926 0.891 0.929
100% 0.894 0.892 0.918

From this table, I observed that the selection ratio of 60% provides the best accuracy for all three defect categories. The accuracy dropped when using fewer features because some important information was removed. The accuracy also dropped when using more features because some redundant information brought noise. Therefore, the 60% threshold is chosen for the final model.

In the classification stage, I constructed an Adaboost-SVM model with a Gaussian radial basis function kernel. The kernel parameter was optimized by grid search in the range [0.01, 10] with a step size of 0.01. The other parameters of the SVM were the penalty parameter \(C\) and the kernel coefficient \(\gamma\). The selected value was \(\gamma = 1.01\). The number of boosting iterations was set to 1000.

Because the dataset is relatively small, I used ten-fold cross-validation to evaluate the performance. In each fold, nine parts of the dataset were used for training and the remaining one part was used for testing. I report the average accuracy, the variance, and the false negative rate for each defect class. The false negative rate is important because it indicates the probability that a defective sample is classified as defect-free, which is critical in industrial quality control.

The confusion matrix for the multi-class classification task is shown below.

Confusion matrix definition for four classes
Actual \ Predicted Crack Gas pore Shrinkage Healthy
Crack TP11 FP12 FP13 FN1
Gas pore FP21 TP22 FP23 FN2
Shrinkage FP31 FP32 TP33 FN3
Healthy FP1 FP2 FP3 TN

For each defect class, the accuracy is defined as the ratio of correctly classified samples to all samples in that class. For example, for the crack class:

$$
\mathrm{Accuracy} = \frac{TP_{11}}{TP_{11} + FP_{12} + FP_{13} + FN_1}
$$

The false negative rate for the crack class is:

$$
\mathrm{FNR} = \frac{FN_1}{TP_{11} + FP_{12} + FP_{13} + FN_1}
$$

One of the ten cross-validation runs is shown in the following table.

One fold of the cross-validation result
Defect class Total Correct Accuracy Misclassified as healthy False negative rate
Crack 112 109 0.973 2 0.017
Gas pore 112 104 0.928 5 0.044
Shrinkage 112 107 0.955 4 0.035
Total defects 336 320 0.952 11 0.032

The averaged results over ten folds are summarized in the next table.

Averaged cross-validation results
Defect class Accuracy mean Accuracy variance False negative rate mean
Crack 0.961 0.0302 0.022
Gas pore 0.921 0.0352 0.046
Shrinkage 0.943 0.0311 0.034
Overall 0.941 0.0321 0.034

I also conducted comparative experiments to evaluate the effectiveness of the proposed feature extraction method. For this purpose, I used each feature family alone as the input to the Adaboost-SVM classifier. The results are shown in the table below.

Comparison of feature extraction methods
Feature set Crack acurracy Crack FNR Gas pore accuracy Gas pore FNR Shrinkage accuracy Shrinkage FNR
Geometric shape 0.938 0.030 0.902 0.052 0.921 0.039
HOG 0.943 0.039 0.912 0.051 0.913 0.041
LBP 0.921 0.041 0.891 0.075 0.901 0.048
Hu moments 0.912 0.039 0.899 0.069 0.897 0.049
Proposed fused set 0.961 0.022 0.921 0.046 0.943 0.034

It is evident that the proposed fused feature set, after SVM-RFE selection, outperforms every single feature family in terms of accuracy and false negative rate. This confirms that combining geometric, texture, and gradient information is beneficial for sand foundry defect recognition.

To further validate the Adaboost-SVM model, I compared it with a standard BP neural network and a random forest classifier using the same selected feature set. The BP network had one hidden layer with five hidden neurons, the SGD optimizer, and a sigmoid activation function. The random forest used ID3 as the base learner, with 30 trees, a maximum depth of 40, and a minimum sample split of 100. The comparison is presented in the following table.

Comparison of classifiers
Classifier Crack accuracy Gas pore accuracy Shrinkage accuracy Overall accuracy Overall FNR
BP neural network 0.937 0.913 0.924 0.924 0.050
Random forest 0.891 0.881 0.902 0.891 0.045
Adaboost-SVM (proposed) 0.961 0.921 0.943 0.941 0.034

As can be seen from the table, the Adaboost-SVM classifier provides the highest accuracy and the lowest false negative rate among all compared models. The overall accuracy reaches 94.1%, which is about two percentage points higher than BP neural network and about five percentage points higher than random forest. In addition, the overall false negative rate is 0.034, which is clearly lower than the other classifiers. This demonstrates the advantages of the proposed ensemble method in the industrial detection of sand foundry defects.

In general, the results indicate that the combination of the multi-feature extraction, SVM-RFE feature selection, and Adaboost-SVM classification is effective for recognizing sand foundry defects in X-ray images. The low false negative rate is especially important because missing a defect can lead to severe consequences in aerospace applications.

Conclusion and Outlook

In this thesis, I have presented a systematic method for sand foundry defect recognition based on X-ray images. The method includes advanced image preprocessing, defect segmentation, multi-feature extraction, feature selection, and ensemble classification. The experimental results on real aerospace casting data show that the proposed method achieves high accuracy and stability for classifying cracks, gas pores, and shrinkage defects.

The main contributions of this work are as follows. First, I analyzed the characteristics of various sand foundry defects and selected appropriate preprocessing and segmentation techniques, such as linear gray transformation, bilateral filtering, Canny edge detection, and adaptive threshold segmentation. Second, I extracted multiple features from different angles, including geometric shape features, Hu moments, LBP texture features, and HOG features. The HOG feature was reduced by PCA to avoid high dimensionality. Third, I used SVM-RFE to eliminate redundant features and obtain a sensitive feature subset that can better represent the differences among defect types. Fourth, I constructed an Adaboost-SVM model that integrates multiple SVM classifiers to improve the generalization and accuracy of recognition. Compared with conventional methods, the proposed method reduces the false negative rate and increases the overall accuracy for sand foundry defects.

Although the proposed method has demonstrated good performance, there is still room for further improvement. In the future, I plan to expand the dataset by collecting more defect images from the production line, especially for rare defect categories. I also intend to optimize the algorithm for real-time processing when the production rate increases. Furthermore, I would like to integrate the recognition model into an online inspection system that can assist the operators in the X-ray room. With the continuous development of deep learning, it would also be interesting to explore end-to-end convolutional neural networks for sand foundry defect recognition. Nevertheless, the machine learning framework proposed in this thesis provides a solid foundation for automated X-ray inspection of sand foundry defects in aerospace castings.

Scroll to Top