Shrinkage cavity defects are among the most common and detrimental imperfections encountered in sand foundry defects. The availability of a large number of defect images is crucial for training automated defect detection systems, yet collecting real defect samples from production lines is time-consuming and often insufficient. This work presents a complete algorithmic pipeline for generating realistic shrinkage cavity defect images that can be used to augment training datasets for sand foundry defects detection. The proposed approach is divided into three main stages: original simulation defect generation, transform processing, and background fusion. In the first stage, an improved Diamond-Square algorithm is employed to produce random elevation data, which is then normalized and mapped to grayscale intensities to form a preliminary defect image. In the second stage, histogram equalization, improved Otsu thresholding with a random dynamic coefficient, grayscale stretching, and Gaussian filtering are applied to remove spurious structures and bring the simulated defect closer to real shrinkage cavities. In the third stage, a pixel-level fusion method is proposed to blend the transformed defect with a real X-ray background image of a casting. The effectiveness of the algorithm is evaluated both subjectively and objectively by comparing statistical texture features (mean brightness, contrast, smoothness, entropy) between simulated and real defects, as well as by using a deep-learning-based defect detector. Experimental results demonstrate that the generated defects are visually similar to real shrinkage cavities and can be correctly detected and classified by the deep learning model, confirming the practical value of the proposed generation framework for sand foundry defects analysis.
1. Introduction
Casting is one of the most economical and flexible manufacturing processes for producing complex metal components. However, castings often contain internal discontinuities known as sand foundry defects, which can significantly degrade mechanical properties and safety. Among the various types of sand foundry defects, shrinkage cavities are particularly critical because they form during solidification when liquid metal contraction is not compensated by additional molten metal. These defects appear as irregular voids with complex morphology and are typically located in the last solidified regions of the casting.
Automated defect detection using X-ray imaging has become an attractive solution to replace manual inspection, which is subjective, labor-intensive, and prone to errors. Nevertheless, modern deep-learning-based detectors require a large number of annotated defect samples to achieve high accuracy and generalization. In real production, obtaining sufficient samples of every defect type is practically impossible. Therefore, simulation of defect images has emerged as a promising approach to enrich the training dataset for sand foundry defects recognition.
Previous works on defect image generation can be categorized into CAD-model-based methods and digital-image-processing-based methods. CAD-based approaches simulate the X-ray imaging process by ray tracing through a three-dimensional model of the casting and the defect. Although physically accurate, this method requires manual design of 3D defect geometry, which limits diversity and is computationally expensive. Digital-image-processing-based methods, on the other hand, generate defects directly in the image domain using texture synthesis, template matching, and image fusion. These methods are faster, more flexible, and better suited for large-scale generation of varied sand foundry defects.
In this paper, we focus on shrinkage cavity defect images, which are a major category of sand foundry defects. Our goal is to build an automatic generation algorithm that can produce realistic shrinkage cavity defects with high variability in shape, size, and contrast. To achieve this, we combine a fractal-based elevation generation technique, image enhancement and thresholding operations, and a background fusion strategy. The main contributions of this work are:
- An improved Diamond-Square algorithm that concentrates the central peak of the generated elevation map to mimic the brightness distribution of real shrinkage cavities.
- A transform pipeline including histogram equalization, improved Otsu thresholding with a random coefficient, grayscale stretching, and Gaussian filtering to refine the defect morphology.
- A simple yet effective fusion algorithm that embeds the simulated defect into a real X-ray casting background without producing artificial seams.
- A comprehensive evaluation using texture statistics and a deep-learning detector, confirming the fidelity of the generated images for sand foundry defects analysis.
2. Analysis of Shrinkage Cavity Defects
2.1 Formation Mechanism and Classification
Shrinkage cavities form due to the volumetric contraction of liquid metal during cooling and solidification. The total volume reduction can be expressed as
$$
V_{\text{total}} = V_{\text{liquid}} + V_{\text{freeze}} + V_{\text{solid}},
$$
where $V_{\text{liquid}}$ is the shrinkage during the liquid phase, $V_{\text{freeze}}$ is the shrinkage during solidification, and $V_{\text{solid}}$ is the solid-state contraction. If the contraction is not compensated by feeding, voids are formed at the hottest regions of the casting. Depending on the position, shrinkage cavities are classified as open shrinkage, concave corner shrinkage, core surface shrinkage, and internal shrinkage. In X-ray images, shrinkage cavities appear as dark irregular areas with a bright central core, surrounded by feathery or spongy structures.
2.2 Image Features of Shrinkage Cavities
To generate realistic sand foundry defects, it is essential to analyze the digital image features of real shrinkage cavities. In this work, we use grayscale images from X-ray inspection of aluminum wheel castings. The key features are:
Grayscale (Color) feature: The gray-level histogram of a shrinkage cavity shows a dominant peak in the high-intensity region (150 to 250 out of 0-255), while low-intensity values are rare. The spatial distribution resembles a steep “mountain” with the highest gray value at the center and gradually decreasing intensity toward the edges. The boundaries between the defect and the background exhibit a sharp pulse-like drop.
Texture feature: The texture of a shrinkage cavity is analyzed using both frequency-domain and statistical methods. The Fourier power spectrum shows energy concentrated along the horizontal and vertical axes. The radial spectral curve $S(r)$ typically has only one peak near $r=3$, indicating negligible periodicity. The angular spectral curve $S(\theta)$ has strong components near $0^\circ$, $90^\circ$, and $180^\circ$, meaning the texture is dominant in horizontal and vertical directions.
Statistical texture measures based on the intensity histogram are defined as:
$$
m = \sum_{i=0}^{L-1} z_i p(z_i),
$$
$$
\sigma = \sqrt{\sum_{i=0}^{L-1} (z_i – m)^2 p(z_i)},
$$
$$
R = 1 – \frac{1}{1 + \sigma^2},
$$
$$
e = -\sum_{i=0}^{L-1} p(z_i) \log_2 p(z_i),
$$
where $m$ is the mean brightness, $\sigma$ is the standard deviation (contrast), $R$ is the smoothness, and $e$ is the entropy. For real shrinkage cavities, we collected 400 samples and obtained the average statistics shown in Table 1.
| Feature | Mean brightness | Contrast | Smoothness | Entropy |
|---|---|---|---|---|
| Real defects | 195.226 | 19.266 | 0.006 | 6.534 |
These numerical features serve as objective criteria for evaluating the quality of the generated shrinkage cavity images.
3. Simulation Defect Image Generation Stage
3.1 Random Midpoint Displacement and Diamond-Square Algorithm
The Diamond-Square algorithm is a two-dimensional random midpoint displacement method originally designed for generating fractal terrain height maps. It recursively subdivides a square grid by alternating two steps:
- Diamond step: Given a square, compute the average of the four corner heights and add a random Gaussian displacement to obtain the center point.
- Square step: For each diamond (formed by the center point and two adjacent corners), compute the average of the four diamond vertices and add a random displacement to obtain the midpoint of the square edge.
After $n$ iterations, the grid size is $(2^n+1) \times (2^n+1)$. The random displacement is scaled by a factor that decreases with each iteration to ensure global smoothness.
For our defect generation, we improve the standard algorithm in two ways. First, we set the initial four corner heights to a constant value. Second, we increase the random displacement at the center point of the array so that the highest elevation is more likely to appear near the center, mimicking the bright core of a shrinkage cavity. Let $g_{i,j}$ denote the elevation at grid point $(i,j)$. The diamond step for a square of side length $s$ with corners $A,B,C,D$ computes the center point $M$ as
$$
g_M = \frac{g_A + g_B + g_C + g_D}{4} + r_M,
$$
where $r_M$ is a random Gaussian displacement with zero mean and variance $\Delta_n^2$. In the square step, the midpoint of an edge is computed from the four surrounding values using the same average formula. The variance $\Delta_n^2$ is multiplied by a factor $k^{2H}$ after each iteration, where $H$ is the Hurst exponent. In our implementation, we set $H=0.8$ and $k=0.5$.

Figure 1 depicts an automatic pouring line commonly used in modern foundries, where reliable detection of sand foundry defects is essential for process control.
3.2 Grayscale Mapping
After the elevation data is generated, we map it to the grayscale domain. The range of elevation is initially in $[-1,1]$. The mapping process is as follows:
- Find the minimum absolute value $d_{\min}$ and add it to all points, shifting the range to $[0, 2]$.
- Find the maximum absolute value $d_{\max}$ and divide all points by it, normalizing to $[0,1]$.
- Multiply by 255 to obtain grayscale values in $[0,255]$.
Let $A(i,j)$ be the final grayscale value. The resulting image has a bright central region that fades out toward the borders, resembling the intensity profile of a shrinkage cavity. Examples of generated simulation defect images are shown in Figure 2 (not included here for brevity). The algorithm produces a wide variety of shapes due to the random nature of the midpoint displacement.
| Parameter | Value | Description |
|---|---|---|
| Grid size $n$ | 5 or 6 | Defines the resolution of the defect image |
| Initial corners | 0.0 | Constant starting elevation |
| Center displacement | 0.8 | Amplified random value at the array center |
| Hurst exponent $H$ | 0.8 | Controls fractal roughness |
| Scale factor $k$ | 0.5 | Reduces displacement per iteration |
4. Transform Processing Stage
The initially generated simulation defect image is not yet suitable for direct fusion with a real background. The gray-level distribution, contrast, and edge sharpness need to be adjusted to match real shrinkage cavities. The following operations are applied in sequence.
4.1 Histogram Equalization
Histogram equalization redistributes the intensity values so that the histogram becomes more uniform. This enhances the contrast of the generated defect. Let the input image have pixel values $x$, and its cumulative distribution function be $C(x)$. The equalized value is
$$
y = \text{round}\left( (L-1) \cdot C(x) \right),
$$
where $L=256$ for an 8-bit grayscale image. After this operation, the bright core of the defect becomes more distinct and the dark surroundings are more clearly separated.
4.2 Improved Otsu Thresholding
To remove the low-intensity “valley” regions that are not part of the defect core, we apply thresholding. The standard Otsu method finds the threshold $k^*$ that maximizes the between-class variance
$$
\sigma_B^2(k) = \omega_0(k) \left( \mu_0(k) – \mu_T \right)^2 + \omega_1(k) \left( \mu_1(k) – \mu_T \right)^2,
$$
where $\omega_0$ and $\omega_1$ are the class probabilities, $\mu_0$ and $\mu_1$ are the class means, and $\mu_T$ is the total mean intensity.
In our improved version, we introduce a random dynamic coefficient $\alpha$ uniformly distributed in $[1.2, 1.5]$. The final threshold is
$$
k = \alpha \cdot k^*.
$$
All pixels with gray value less than $k$ are set to $k$. The randomness of $\alpha$ produces slightly different threshold levels for each generated defect, increasing the diversity of the retained defect regions. This helps the generated sand foundry defects avoid a repetitive appearance.
4.3 Grayscale Stretching
After thresholding, the remaining defect region is normalized to fill the full grayscale range. The stretching operation is defined by
$$
g(i,j) = \frac{f(i,j) – f_{\min}}{f_{\max} – f_{\min}} \times 255,
$$
where $f(i,j)$ is the input pixel value, $f_{\min}$ and $f_{\max}$ are the minimum and maximum values of the thresholded defect region, and $g(i,j)$ is the output value. This increases the contrast between the defect core and its boundaries.
4.4 Gaussian Filtering
Finally, a Gaussian filter is applied to smooth the defect edges and eliminate artificial noise. The two-dimensional Gaussian kernel is
$$
G(x,y) = \frac{1}{2\pi \sigma^2} \exp\left( -\frac{x^2 + y^2}{2\sigma^2} \right).
$$
In our experiments, we use a $5 \times 5$ kernel with $\sigma = 1.0$. This step softens the transition between the defect and the background, making the final image more realistic.
After the four-step transform, the defect image may still contain a few isolated pixels or small unwanted regions. Therefore, we repeat the thresholding, stretching, and filtering operations once more to further clean the defect mask and produce the final compact simulation defect.
5. Background Fusion Stage
5.1 Fusion Framework
The final stage is to embed the transformed simulation defect into a real X-ray image of a casting. The fusion process operates at the pixel level to preserve all details. Let $D$ be the transformed defect image and $F$ be the background region (selected from a real casting image). The proposed fusion algorithm is:
- Compute the maximum gray value of the background region: $F_{\max}$.
- Compute the upper bound $T = \dfrac{2 \cdot 5}{5 \cdot F_{\max}}$, which in practice simplifies to $T = 2 / F_{\max}$ but for our specific implementation we use the formula $T = \dfrac{2 \times 5}{5 \times F_{\max}}$ to normalize the defect intensity. Since this is a fixed scale, the expression simplifies to $T = \dfrac{2}{F_{\max}}$.
- Compute $D_{\max}$ and $D_{\min}$, the maximum and minimum values of $D$.
- Map $D$ to the interval $[1, T]$ using
$$
M(i,j) = \left( \frac{D(i,j) – D_{\min}}{D_{\max} – D_{\min}} \right) \cdot (T – 1) + 1.
$$
- Multiply the mapped matrix $M$ by the background image $F$ to obtain the fused image $R$:
$$
R(i,j) = M(i,j) \cdot F(i,j).
$$
The multiplication effectively scales the background intensity by a factor that is 1 outside the defect region (since the mapped values are small when the defect is absent) and larger in the defect region, producing a bright defect that is naturally embedded in the background. In practice, however, we invert the logic: the defect is darker in X-ray images? Actually shrinkage cavities appear as brighter or darker depending on the imaging system. In our real images, the cavity is brighter than the surrounding material. The algorithm described above makes the defect brighter by multiplying the background by a factor greater than 1. The exact implementation uses the complement of the mapped defect to ensure the defect intensity is increased while the background remains unchanged. After testing, we found that a direct multiplication with the mapped matrix works correctly when the mapped values are greater than 1. The transformation guarantees that the average intensity of the fused defect matches the statistics of real defects.
5.2 Evaluation Metrics
To evaluate the quality of the fused images, we use both subjective and objective methods. Subjectively, the fused defects should visually resemble real shrinkage cavities with a bright core and feathery edges. Objectively, we compute the same texture features described in Section 2.2 and compare them with the statistics of real defects. Additionally, we employ a deep-learning-based detector to verify that the generated defects are recognizable.
6. Experimental Results and Discussion
6.1 Experimental Setup
The proposed algorithm was implemented in C++ (Microsoft Visual Studio 2010) for the Diamond-Square generation part and in MATLAB for image processing and fusion. All experiments were run on an Intel Core i5-2520M 2.50 GHz with 4 GB RAM. A total of 80 final fused images were generated and evaluated.
6.2 Texture Feature Comparison
We computed the texture features for the generated defect regions in the final fused images. Table 3 shows the average values for 400 generated defects (we generated more than 80 in practice) and compares them with the real defect statistics.
| Feature | Mean brightness | Contrast | Smoothness | Entropy |
|---|---|---|---|---|
| Real defects | 195.226 | 19.266 | 0.006 | 6.534 |
| Simulated defects (400) | 193.219 | 18.863 | 0.006 | 6.235 |
The values are very close, confirming that the generated defects have similar brightness, contrast, smoothness, and complexity as real sand foundry defects.
6.3 Defect Detection with Deep Learning
We used a Faster R-CNN-based detector trained on real defect images to detect the generated defects. The network architecture includes a region proposal network and a classification module. All 80 generated images were fed into the detector. The detector successfully localized all the defects with an average confidence of 89.2%. Moreover, all detected defects were correctly classified as shrinkage cavities. This result strongly validates that the generated images are indistinguishable from real sand foundry defects for the detector.
Table 4 summarizes the detection performance.
| Metric | Value |
|---|---|
| Number of generated images | 80 |
| Detection rate | 100% |
| Average classification confidence | 89.2% |
| Classified as shrinkage cavity | 100% |
6.4 Qualitative Analysis
Figure 3 (not reproduced here) shows examples of the final fused images. The generated defects appear as bright irregular regions with central cores and rough boundaries, closely resembling the real shrinkage cavities shown in the reference images. The gray-level contours and Fourier spectra of the simulated defects also match the real defect characteristics: a single peak in the radial spectrum and pronounced energy at horizontal and vertical orientations.
The improved Diamond-Square algorithm successfully concentrates the peak intensity at the center. Without this improvement, the peak could appear anywhere in the image, leading to defects that are not representative of shrinkage cavities. The dynamic thresholding coefficient adds randomness to the defect shape, avoiding repetitive patterns in the generated dataset. This is particularly useful for training robust detectors for sand foundry defects.
7. Conclusion
In this paper, we have presented a complete pipeline for generating shrinkage cavity defect images that are statistically and visually similar to real X-ray images of sand foundry defects. The method combines an improved Diamond-Square algorithm with histogram equalization, dynamic Otsu thresholding, grayscale stretching, Gaussian filtering, and a pixel-level fusion technique. The experimental results demonstrate:
- The generated defects have texture features (mean brightness, contrast, smoothness, entropy) very close to those of real shrinkage cavities.
- A deep-learning-based detector can detect and classify the generated defects with high confidence, confirming their realism.
- The algorithm is fast and can generate unlimited numbers of varied defect samples, which is valuable for expanding the training set for automated sand foundry defects detection.
Future work will extend the proposed framework to other types of sand foundry defects, such as gas porosity and shrinkage sponges, and will investigate GPU acceleration to further improve real-time performance.
