I have carried out an in-depth study of sand foundry defect detection with a machine-vision approach. In actual foundry production, casting surfaces often contain cracks, blowholes, shrinkage cavities, and other defects caused by imperfect process conditions and environmental variability. Those surface anomalies directly degrade product quality, especially for cast safety components such as automobile brake discs. In many domestic manufacturing enterprises, the final surface inspection still relies on human visual judgment; such manual inspection is subjective, easily affected by fatigue, and too slow for modern high-volume production. Therefore, I have designed a machine-vision-based inspection framework that can localize the casting, segment suspicious regions, classify defect types, and reject defective products online. Throughout this article, I will emphasize the central problem of sand foundry defect detection and the solutions I used to solve it.
1. Introduction and Problem Statement
Castings are widely used in automotive components, aerospace parts, medical equipment, furniture fittings, and many other industrial fields. The surface quality of castings is a critical factor determining their service performance. The presence of surface defects can cause stress concentration, reduce fatigue life, and even lead to catastrophic failure in safety-critical parts. The term sand foundry defect refers to any surface anomaly generated during molding, pouring, solidification, shakeout, or post-processing of sand-cast components. Common sand foundry defect classes include gas holes, shrinkage cavities, hot tears, cold cracks, sand inclusions, and rust-like stains. Some of these defects are genuine discontinuities in the material, while others are harmless discolorations that can easily be mistaken for defects by imaging systems.
Traditional non-destructive testing methods can be used for casting inspection. For internal flaws, radiographic testing and ultrasonic testing are common. For surface defects, the industry often uses liquid penetrant testing, magnetic particle testing, and eddy current testing. The table below summarizes the conventional techniques and their main limitations.
| Technique | Physical Principle | Advantages | Limitations |
|---|---|---|---|
| Liquid Penetrant Testing | Capillary action of dye penetrant | High sensitivity to open surface flaws | Multistep, slow, labor intensive |
| Magnetic Particle Testing | Leakage flux around magnetic discontinuities | Direct visual indication of defects | Only ferromagnetic materials; limited coverage |
| Eddy Current Testing | Induced eddy current distortion | Fast and non-contact | Conductive materials only; cannot characterize shape/size |
Although these techniques are reliable in specific circumstances, they are generally off-line and slow. A vision-based system, on the other hand, can provide non-contact, robust, and efficient inspection. The key motivation of my research is to build a real-time visual inspection system that can detect and classify sand foundry defect categories automatically. I selected the automobile brake disc as the research object because brake disc surface quality is directly related to braking performance and road safety. The main technical challenges are:
- The foundry workshop environment contains dust, varying illumination, and vibration from conveyors.
- The acquired image mixes the brake disc with a complex industrial background.
- Defect regions are relatively small compared with the whole casting surface.
- Different defect types can have similar gray-level appearances, which complicates classification.
- Pseudo-defects such as rust stains may be confused with real defects.
To solve these problems, I developed a complete machine-vision inspection pipeline consisting of image acquisition hardware, image denoising, object localization, suspicious-region segmentation, feature extraction, dimensionality reduction, and support vector machine classification. I verified the whole system on a physical test platform using 100 brake disc samples.
2. Analysis of the Detection Object and Technical Indicators
The brake disc is a typical sand-cast component. Its working surface is the annular face that contacts the brake pad. During braking, the brake caliper pushes the friction material against both sides of the disc, generating friction to slow the vehicle. Any surface flaw on this face can reduce the effective contact area and cause unstable braking. Therefore, the inspection algorithm must specifically analyze the brake disc surface region rather than the whole image.
I analyzed the commonly observed sand foundry defect types and their causes. The table below lists the main defect classes considered in this study.
| Defect Type | Morphology | Gray-Level Character in Image | Primary Cause |
|---|---|---|---|
| Blowhole / Gas Hole | Round or nearly round; smooth inner wall | Dark, relatively uniform interior | Gas entrapped during pouring; damp or rusty charge |
| Shrinkage Cavity | Irregular shape; rough inner wall; dendritic structure | Dark with internal gray variations | Improper solidification; high pouring temperature |
| Crack | Narrow, elongated path; straight or curved | Very dark, high contrast edge | Thermal stress or excessive cooling stress |
| Rust Stain (pseudo-defect) | Large irregular stained area | Moderately dark; low contrast | Oxidation on the surface, not a true discontinuity |
I set the following technical indicators for the online inspection system based on production needs:
| Indicator | Requirement |
|---|---|
| Detection correctness for product acceptance | At least 98% of defective parts must be rejected; some good parts may be over-rejected |
| Classification accuracy among accepted defective parts | Misclassification rate of defect type must be lower than 15% |
| Average inspection speed | No more than 5 seconds per part |
These indicators guided my selection of cameras, lenses, lighting, and algorithms. They also provided quantitative criteria for the final system evaluation.
3. Hardware Architecture of the Machine-Vision Inspection System
The hardware system is responsible for stable image acquisition. It must suppress ambient light variations and provide sufficient contrast for the detection of sand foundry defect features. I built a dark-field-like structure with a conveyor roller, a stopper, photoelectric sensors, and an aluminum alloy supporting frame covered with black cloth. In this environment, the light inside the camera field of view is fully controlled by artificial lighting.

The image above shows an automatic pouring line commonly used in a modern sand foundry. The presence of such automated equipment creates the need for a reliable inline sand foundry defect inspection system that can keep pace with the production line.
3.1 Camera Selection
I chose a monochrome CCD industrial camera because the brake disc surface is gray or bright metallic without significant color information. A monochrome CCD offers higher effective sensitivity, lower noise, and a smaller data volume than a color sensor. The camera has a resolution of 2456×2058 pixels, an optical format of 2/3 inch, and a pixel size of 3.45 μm. It supports Gigabit Ethernet output, which allows fast transfer of high-resolution images to the computer. The maximum frame rate is 15 fps at full resolution, which is sufficient for the low-speed conveyor-based inspection.
3.2 Lens Selection
The lens determines the field of view, depth of field, and optical resolution. I selected a fixed-focal-length lens with a focal length of 12 mm, an aperture range from F1.4 to F16, and a C-mount interface. The lens can cover a 2/3 inch sensor format. With the working distance defined by the conveyor and stopper geometry, this lens provides a field of view that covers the complete brake disc surface while retaining enough spatial resolution to detect small defects.
3.3 Lighting Design
Lighting is the most important hardware factor in visual inspection. I used LED bar lights placed at a high angle to the casting surface. This configuration emphasizes topographic features such as pits, cracks, and cavities while reducing the influence of ambient illumination. LED sources are stable, have long lifetimes, and produce relatively little heat. The black cloth enclosure further prevents external light from interfering with the captured image.
3.4 Hardware Platform and Control Flow
I placed two pairs of through-beam photoelectric sensors on both sides of the conveyor. When the first sensor is triggered, the stopper rises and the first conveyor section stops, while the second conveyor section continues to move the brake disc toward the inspection position. When the second sensor is triggered, the second roller stops and the camera acquires an image. The computer then processes the image and outputs the inspection result. After processing, the stopper drops and both roller sections resume movement. This control flow guarantees that every brake disc stops at almost the same position for image acquisition, which simplifies the subsequent localization algorithm.
4. Image Processing Methods for Sand Foundry Defect Detection
The raw image captured by the camera contains both useful surface information and heavy noise. Direct processing of such an image will lead to unreliable results. I designed a multi-step image processing pipeline: denoising, object localization, suspicious defect region segmentation, and morphological post-processing.
4.1 Image Denoising
Image noise is generated during sensor exposure, signal transmission, and under the influence of mechanical vibration or dust. Common denoising methods include mean filtering, Gaussian filtering, median filtering, and bilateral filtering. To choose the best filter for the sand foundry defect image, I compared their peak signal-to-noise ratio (PSNR) after processing.
The mean filter computes the average gray value inside a neighborhood window:
$$g(x,y) = \frac{1}{K} \sum_{(i,j)\in S} f(i,j)$$
where S is the set of pixel coordinates in the neighborhood and K is the number of pixels in S. Mean filtering can effectively reduce Gaussian noise but tends to blur edges, which are important for defect boundary detection.
The Gaussian filter uses a two-dimensional Gaussian kernel as the weighting function:
$$g(x,y) = \frac{1}{2\pi\sigma^2} \exp\left(-\frac{x^2+y^2}{2\sigma^2}\right)$$
The standard deviation σ controls the smoothing strength. A larger σ achieves more noise suppression but also loses more image detail.
The median filter replaces the central pixel with the median of the neighborhood:
$$g(x,y) = \mathrm{Med}\{f(i,j) \mid (i,j)\in S\}$$
Median filtering is especially effective for impulse noise and salt-and-pepper noise, but it can distort thin structures such as cracks if the window is too large.
The bilateral filter combines spatial proximity and intensity similarity:
$$g(x,y) = \frac{\sum_{(i,j)} f(i,j) w(x,y,i,j)}{\sum_{(i,j)} w(x,y,i,j)}$$
with the weight
$$w(x,y,i,j) = \exp\left(-\frac{(x-i)^2+(y-j)^2}{2\sigma_d^2} – \frac{\|f(x,y)-f(i,j)\|^2}{2\sigma_r^2}\right)$$
where σd controls spatial smoothing and σr controls intensity smoothing. In my experiments, I used a 5×5 window for all filters. The PSNR results are summarized below.
| Filter | PSNR (dB) |
|---|---|
| Mean filter | 39.789 |
| Gaussian filter | 40.990 |
| Median filter | 39.659 |
| Bilateral filter | 46.279 |
The bilateral filter achieved the highest PSNR, so I selected it as the denoising operator in the final system. This filter preserves edge sharpness while suppressing noise, which is essential for the subsequent detection of sand foundry defect boundaries.
4.2 Template Matching for Brake Disc Localization
After denoising, the image still contains the conveyor, stopper, and other background parts. I needed to segment the brake disc surface region from the complex background. Since the camera position is fixed and the brake disc only translates within the field of view, I selected a gray-value-based template matching algorithm rather than a feature-based matching method. The important advantage of gray-value matching is its simplicity and speed when no rotation or scale variation occurs.
I created a static template from a reference brake disc image. The template creation process used background subtraction, Otsu thresholding, and morphological reconstruction to extract the clean disc region from the background. The resulting binary mask was multiplied with the original image to produce the template image.
The similarity measure I adopted is the normalized correlation coefficient:
$$R(i,j) = \frac{\sum_{s=1}^{M}\sum_{t=1}^{N} \left(S_{i,j}(s,t)-E(S_{i,j})\right)\left(T(s,t)-E(T)\right)}{\sqrt{\sum_{s=1}^{M}\sum_{t=1}^{N} \left(S_{i,j}(s,t)-E(S_{i,j})\right)^2} \sqrt{\sum_{s=1}^{M}\sum_{t=1}^{N} \left(T(s,t)-E(T)\right)^2}}$$
where Si,j is the sub-image at position (i,j), T is the template, E(·) denotes the mean gray value, M and N are the template width and height, and R(i,j) gives a value in [−1,1]. A value close to 1 means a perfect match.
Computing the similarity over the entire image is time-consuming. To accelerate the matching process, I introduced two optimization strategies.
First, I used a similarity-termination criterion. When calculating the partial correlation at pixel k of n total pixels, I stopped the computation if:
$$R_k < R_{\min} – 1 + \frac{k}{n}$$
where Rk is the partial similarity after k pixels and Rmin is the desired threshold. I set Rmin=0.75 because the controlled industrial environment does not produce severe occlusions.
Second, I used an image pyramid strategy. I built several down-sampled versions of the image and template. At each level, the image is filtered with a 2×2 mean kernel and then decimated. Matching begins at the lowest-resolution level to obtain a rough candidate location, then refines the location level by level until the original resolution is reached. This strategy dramatically reduces the computation time. The average localization time over 20 test images was 289 ms, which was much faster than the original 879 ms.
4.3 Defect Region Segmentation
After localization, I masked out the background and only kept the brake disc surface. The surface defects are generally darker than the normal casting background because they are concave and scatter light away from the camera. Therefore, I used thresholding to separate the defect regions from the background.
I compared two threshold selection methods: the Otsu method and the maximum entropy method.
For an image with gray levels in the range [0,L−1], let p(i) be the probability of gray level i. If a threshold k divides the pixels into two classes C0 and C1, the class probabilities are:
$$P_0 = \sum_{i=0}^{k} p(i)$$
$$P_1 = 1 – P_0$$
The Otsu method selects the threshold that maximizes the between-class variance:
$$\sigma^2(k) = P_0(\mu_0 – k)^2 + P_1(\mu_1 – k)^2$$
where μ0 and μ1 are the class means. The optimal threshold is:
$$k^* = \arg\max_{0\le k\le L-1} \sigma^2(k)$$
The maximum entropy method, by contrast, maximizes the total entropy of the foreground and background:
$$H(k) = -P_0 \ln P_0 – (1-P_0)\ln(1-P_0)$$
and
$$k^* = \arg\max_{0\le k\le L-1} H(k)$$
In my experiments, the Otsu method failed to separate small defect regions because the defect area is very small compared with the entire brake disc surface. The maximum entropy method gave better segmentation results. Therefore, I selected the maximum entropy method as the thresholding algorithm.
After thresholding, I applied morphological opening to remove small noise points. Let A be the binary image and B be the structuring element. The opening operation is defined as:
$$A \circ B = (A \ominus B) \oplus B$$
The opening operation removes thin protrusions and small isolated noise regions while preserving the overall shape of the actual defect areas. Because the system must not miss any real defective part, I chose an expansion structuring element slightly larger than the erosion element during the opening operation. This ensures that genuine defect regions are retained even if tiny parts of them are removed during erosion.
I used the total number of foreground pixels after segmentation to judge whether the surface has a defect. The table below shows typical foreground pixel counts for defective and non-defective surfaces.
| Defective Surface Sample | Foreground Pixels | Non-defective Surface Sample | Foreground Pixels |
|---|---|---|---|
| 1 | 963 | 1 | 232829 |
| 2 | 1362 | 2 | 273668 |
| 3 | 5793 | 3 | 385106 |
| 4 | 13117 | 4 | 327517 |
The foreground pixel count for defective surfaces is one to two orders of magnitude smaller than that for non-defective surfaces. I set a threshold of 100,000 pixels: if the foreground count is less than this threshold, the part is considered suspicious and sent to the classification stage; otherwise, it is considered a good product. This pixel-count criterion is simple and reliable for the initial screening of sand foundry defect candidates.
After segmentation, I used the minimum enclosing rectangle of each connected component to crop each suspicious region into an individual small image. This makes the subsequent feature extraction and classification more efficient and more accurate.
5. Feature Extraction and Dimensionality Reduction for Sand Foundry Defect Classification
The segmented suspicious regions contain the potential defect areas. To identify the exact type of sand foundry defect, I extracted geometric features, invariant moment features, and texture features from these small image patches. Feature quality directly influences classifier performance.
5.1 Geometric Shape Features
The shape of a defect region provides useful discriminative information. Blowholes tend to be round, shrinkage cavities are more irregular, cracks are long and narrow, and rust stains are large and amorphous. I extracted the following geometric features:
The area A of a defect region is the number of pixels in the region:
$$A = \sum_{i=0}^{M-1}\sum_{j=0}^{N-1} I(i,j)$$
The perimeter L is computed from the 8-connected chain code:
$$L = \sqrt{2}N_o + N_e$$
where No is the number of odd chain-code directions and Ne is the number of even chain-code directions.
The circularity C measures how close the shape is to a circle:
$$C = \frac{A}{A_c}$$
where Ac is the area of the minimum circumscribed circle. A value close to 1 indicates a round shape.
The rectangularity R measures how close the region is to its minimum enclosing rectangle:
$$R = \frac{A}{A_R}$$
where AR is the area of the minimum enclosing rectangle.
The aspect ratio W is the ratio of the length to the width of the minimum enclosing rectangle:
$$W = \frac{l}{w}$$
A high aspect ratio indicates a long and thin shape, which is typical for cracks.
The table below shows sample geometric features for different defect types.
| Sample | Area | Perimeter | Circularity | Rectangularity | Aspect Ratio |
|---|---|---|---|---|---|
| Blowhole 1 | 431 | 79.70 | 0.628 | 0.757 | 1.548 |
| Blowhole 2 | 219 | 55.70 | 0.702 | 0.805 | 1.382 |
| Shrinkage 1 | 1244 | 147.98 | 0.479 | 0.758 | 1.535 |
| Shrinkage 2 | 807 | 153.26 | 0.330 | 0.681 | 2.878 |
| Crack 1 | 7744 | 971.21 | 0.058 | 0.430 | 10.768 |
| Crack 2 | 4674 | 583.19 | 0.125 | 0.703 | 6.836 |
| Rust stain 1 | 7564 | 444.25 | 0.348 | 0.774 | 2.395 |
| Rust stain 2 | 2053 | 206.65 | 0.371 | 0.745 | 1.917 |
In addition to these simple geometric descriptors, I also used the seven Hu invariant moments. The Hu moments are based on normalized central moments and are invariant to translation, scaling, and rotation. For an image f(x,y), the p+q order geometric moment is:
$$m_{pq} = \sum_{i=1}^{M}\sum_{j=1}^{N} i^p j^q f(i,j)$$
The central moment is:
$$\mu_{pq} = \sum_{i=1}^{M}\sum_{j=1}^{N} (i-\bar{i})^p (j-\bar{j})^q f(i,j)$$
where $\bar{i}=m_{10}/m_{00}$ and $\bar{j}=m_{01}/m_{00}$. The normalized central moment is:
$$\eta_{pq} = \frac{\mu_{pq}}{\mu_{00}^{\gamma}}, \quad \gamma = \frac{p+q}{2}+1$$
The Hu moment features are then computed from the second- and third-order normalized central moments. They provide a compact numerical descriptor of the defect shape. In my classification feature vector, I included five simple geometric features and seven Hu moments, resulting in a set of 12 geometric shape features.
5.2 Texture Features and Local Binary Patterns
Shape features alone cannot fully distinguish between defects because some shrinkage cavities and rust stains have similar shapes. I therefore added texture features based on Local Binary Patterns (LBP). LBP describes the local spatial structure of an image and is robust to monotonic gray-level changes.
The original LBP operator compares the center pixel of a 3×3 neighborhood with its eight neighboring pixels:
$$LBP(x_c,y_c) = \sum_{p=0}^{P-1} s(i_p – i_c) 2^p$$
where ic is the gray value of the center pixel, ip are the gray values of the neighboring pixels, and
$$s(x)= \begin{cases} 1, & x>0 \\ 0, & x\le 0 \end{cases}$$
To handle textures at different scales, I used the circular neighborhood extension with radius R and P sampling points. If a sampling point does not coincide with an integer pixel coordinate, bilinear interpolation is used to obtain its value.
I also used the rotation-invariant version of LBP. The rotated LBP value is defined as:
$$LBP_{P,R}^{ri} = \min \{ ROR(LBP_{P,R}, i) \mid i=0,1,\ldots,P-1 \}$$
where ROR denotes circular bitwise rotation. This operation makes the LBP descriptor insensitive to image rotation, which is beneficial because the same defect can appear at different orientations on the brake disc surface.
To reduce the dimension of the LBP descriptor, I used uniform patterns. A local binary pattern is called uniform if the number of bitwise transitions between 0 and 1 is at most two. Uniform patterns represent the most informative local structures, while non-uniform patterns are often caused by noise. For a neighborhood with P sampling points, the number of uniform patterns is P(P−1)+2. By assigning all non-uniform patterns to a single bin, the dimension of the LBP histogram becomes P(P−1)+3. In my implementation, I used P=8 and R=1, so the uniform LBP histogram had 59 dimensions.
The LBP texture features capture the roughness of the defect interior. For example, shrinkage cavities often exhibit rough internal surfaces, while blowholes have smoother interiors. This distinction helps the classifier separate blowhole defects from shrinkage cavities.
5.3 Principal Component Analysis for Feature Dimensionality Reduction
Combining 12 geometric features and 59 LBP texture features yields a 71-dimensional feature vector. Some of these features are redundant or correlated. High-dimensional feature vectors increase training time and can cause overfitting in the classifier. I therefore used Principal Component Analysis (PCA) to reduce the dimensionality while retaining most of the information.
Let X be the m×n data matrix, where m is the number of samples and n is the number of original features. I first subtract the mean of each feature column. The covariance matrix is:
$$\Sigma = \frac{1}{m-1} (X-\bar{X})^T (X-\bar{X})$$
PCA seeks the eigenvectors of Σ corresponding to the largest eigenvalues. The first principal component w1 maximizes the variance of the projected data:
$$\sigma_1^2 = \mathbf{w}_1^T \Sigma \mathbf{w}_1, \quad \mathbf{w}_1^T \mathbf{w}_1 = 1$$
This leads to the eigenvalue equation:
$$\Sigma \mathbf{w}_1 = \lambda_1 \mathbf{w}_1$$
where λ1 is the largest eigenvalue. In general, the k-th principal component corresponds to the k-th largest eigenvalue. The cumulative contribution rate of the first k principal components is:
$$\gamma_k = \frac{\sum_{i=1}^{k}\lambda_i}{\sum_{i=1}^{n}\lambda_i}$$
In my experiments, the cumulative contribution rate of the first six principal components exceeded 99.88%. Therefore, I replaced the original 71-dimensional defect feature vector with a 6-dimensional PCA feature vector. This greatly simplified the classification problem without losing significant information.
6. Support Vector Machine for Sand Foundry Defect Classification
Support Vector Machine (SVM) is well suited for small-sample, nonlinear, high-dimensional pattern recognition problems. Because there is no large public dataset of sand foundry defect images, my training set is relatively small. SVM provides good generalization performance in this situation.
6.1 SVM Principle
For binary classification, SVM finds a separating hyperplane that maximizes the margin between positive and negative samples. The decision function is:
$$y(x) = \mathrm{sign}\left(\sum_{i=1}^{n} \alpha_i y_i K(x_i, x_j) + b\right)$$
where αi are Lagrange multipliers, yi are class labels, K(xi,xj) is the kernel function, and b is the bias.
The optimal hyperplane is found by solving the following optimization problem:
$$\min \frac{1}{2}\|\mathbf{w}\|^2 + C\sum_{i=1}^{N}\xi_i$$
subject to
$$y_i(\mathbf{w}\cdot\mathbf{x}_i + b) \ge 1 – \xi_i, \quad \xi_i \ge 0$$
Here, C is the penalty parameter that balances the margin width and the classification error, and ξi are slack variables that handle non-separable samples.
The dual formulation is:
$$\max_{\alpha} \left[\sum_{i=1}^{l}\alpha_i – \frac{1}{2}\sum_{i=1}^{l}\sum_{j=1}^{l}\alpha_i\alpha_j y_i y_j K(x_i,x_j)\right]$$
subject to
$$\sum_{i=1}^{l} \alpha_i y_i = 0, \quad 0\le \alpha_i \le C$$
After solving for α*, the bias b* is computed, and the final classification function is obtained. For multi-class classification, I used a one-versus-one strategy, which constructs binary classifiers between every pair of classes and then applies a voting scheme.
6.2 Kernel Selection and Parameter Optimization
I compared four common kernel functions: linear, polynomial, radial basis function (RBF), and sigmoid. The kernel functions are:
Linear kernel:
$$K(x_i,x_j) = x_i^T x_j$$
Polynomial kernel:
$$K(x_i,x_j) = (x_i\cdot x_j + 1)^d$$
RBF kernel:
$$K(x_i,x_j) = \exp\left(-\gamma \|x_i – x_j\|^2\right)$$
Sigmoid kernel:
$$K(x_i,x_j) = \tanh(\eta x_i\cdot x_j + c)$$
I trained four SVM classifiers using the same training set and tested them on the same validation set. The recognition accuracies are listed below.
| Kernel | Classification Accuracy (%) |
|---|---|
| Linear | 68.57 |
| Polynomial | 65.71 |
| Radial Basis Function | 78.57 |
| Sigmoid | 72.86 |
The RBF kernel gave the best accuracy. Therefore, I chose the RBF kernel for the final classifier. The RBF kernel has two important parameters: the penalty factor C and the kernel coefficient γ. To obtain a reliable model, I used cross-validation to search the parameter space. The search ranges were:
$$C \in [2^{-3}, 2^{10}], \quad \gamma \in [2^{-5}, 2^{5}]$$
I used 80 sample regions, including 20 samples from each defect class: blowhole, shrinkage cavity, crack, and rust stain. The cross-validation results showed that the best parameter pair was:
$$C = 512, \quad \gamma = 0.125$$
The corresponding overall classification accuracy was 86.48%. This result met the requirement that the misclassification rate of defect types be lower than 15%.
7. Software Design and Experimental Validation
7.1 Software System
I developed a software system with a friendly graphical interface to control the inspection process and display results. The software includes the following functional modules:
- Detection control: start and stop detection, select trigger mode, configure serial port.
- Image acquisition and display: capture images and show them in real time.
- Counting and display: show the number of inspected parts, good parts, and each defect class.
- Timing and display: show inspection time for each part and total operating time.
- Production log: store original images, intermediate processed images, classification results, and timestamps for later analysis.
The software interface is divided into two main areas. The left side displays the current camera image, the localization result, and the defect segmentation result. The right side contains parameter settings and real-time counter values. When the camera or the serial port is disconnected, the software displays an alarm message to prevent incorrect operation.
7.2 System Test
I evaluated the complete inspection system using 100 brake disc samples. The set included 40 brake discs without rust or defects, and 15 brake discs from each of the following categories: blowhole, shrinkage cavity, crack, and rust stain. The rust-stained discs were considered qualified products because rust is not a true structural defect, but they may be wrongly classified as defective if the system is not trained properly.
The confusion matrix below shows the experimental results.
| Actual | Good | Blowhole | Shrinkage | Crack | Rust Stain |
|---|---|---|---|---|---|
| Good (no rust) | 40 | 0 | 0 | 0 | 0 |
| Blowhole | 0 | 12 | 3 | 0 | 0 |
| Shrinkage | 0 | 1 | 14 | 0 | 0 |
| Crack | 0 | 0 | 0 | 15 | 0 |
| Rust stain | 1 | 0 | 1 | 0 | 13 |
I computed the performance metrics as follows:
$$\text{Miss rate} = \frac{\text{defective samples not detected}}{\text{total samples}} \times 100\%$$
$$\text{Detection rate} = \frac{\text{samples with correct classification}}{\text{total samples}} \times 100\%$$
$$\text{Misclassification rate} = \frac{\text{misclassified samples}}{\text{total samples}} \times 100\%$$
$$\text{Inspection time} = \frac{\text{total inspection time}}{\text{total samples}}$$
From the confusion matrix, the miss rate was 0%, meaning that every truly defective part was detected and rejected. One rust-stained part was classified as good, and one good part was classified as defective. The final correct rate for product qualification judgment was 99%, which satisfies the requirement of at least 98% detection correctness.
For the four suspicious categories, the classification accuracy among defective samples was:
$$\frac{12+14+15+13}{60} \times 100\% = 90\%$$
The misclassification rate for defect type was:
$$\frac{3+1+1}{45} \times 100\% = 8.89\%$$
This is below the required 15%. The most common confusion was between blowholes and shrinkage cavities, which is reasonable because the two defect types can be similar in two-dimensional gray-level images.
The average processing time for different defect classes is shown below.
| Part Type | Average Inspection Time (s) |
|---|---|
| Good (no rust) | 0.594 |
| Blowhole | 1.479 |
| Shrinkage cavity | 1.487 |
| Crack | 1.495 |
| Rust stain | 1.492 |
The good parts required less time because they did not enter the SVM classification stage. The maximum inspection time was less than 1.5 seconds, which is far below the 5-second limit. Therefore, the system satisfies the speed requirement for online inspection.
7.3 Discussion
The experimental results confirm that the proposed image processing and classification algorithms are suitable for real-time sand foundry defect detection. The combination of maximum entropy segmentation and morphological opening can accurately locate suspicious areas. The PCA-based feature reduction improves classifier efficiency without sacrificing accuracy. The SVM with RBF kernel and cross-validated parameters provides reliable classification of common sand foundry defect categories.
One limitation is that the system operates on two-dimensional images and cannot directly measure defect depth. A deeper shrinkage cavity and a shallow rust stain may occasionally have similar gray-level distributions, causing misclassification. Future work could incorporate structured light or laser triangulation to obtain depth information. Another direction is to use deep learning with a larger dataset to automatically learn more discriminative features.
I also noticed that the template matching algorithm is robust under controlled lighting but might fail if the workpiece undergoes rotation or scale changes. In practical production, the brake disc is always placed on the same conveyor and stopped at the same position, so this limitation is acceptable. For other casting products with different shapes, the template could be regenerated using the same background-subtraction and thresholding procedure.
8. Conclusion and Future Work
In this study, I developed a machine-vision-based inspection system for sand foundry defect detection and classification. I first analyzed the characteristics of typical casting surface defects and defined the technical requirements for the system. Then I designed a hardware platform with a CCD camera, a fixed-focal-length lens, LED lighting, a conveyor, and a stopper. I selected the bilateral filter for denoising because it achieved the highest PSNR. I implemented an accelerated template matching algorithm with a similarity-termination strategy and an image pyramid to localize the brake disc in complex industrial scenes. For defect region segmentation, I used the maximum entropy thresholding method followed by morphological opening to suppress noise. The number of foreground pixels was used to judge whether a surface had a suspicious defect.
For defect classification, I extracted geometric features, Hu moments, and uniform LBP texture features. Principal Component Analysis reduced the original high-dimensional feature vector to six principal components while retaining 99.88% of the information. I trained a support vector machine with the RBF kernel and selected the optimal parameters C=512 and γ=0.125 by cross-validation. The final classifier achieved a classification accuracy of 90% on the tested defect samples and a misclassification rate of 8.89% for defect types.
The complete inspection system was tested on 100 brake disc samples. The experimental results met all the required technical indicators: 0% miss rate for real defects, 99% correctness for product qualification, and an average inspection time below 1.5 seconds per part. The proposed method is therefore feasible and effective for online sand foundry defect inspection.
Future research can focus on the following aspects. First, the method should be extended to other types of castings to verify its generality. Second, depth information should be introduced into the feature set to better separate shallow surface stains from true cavities. Third, more defect samples should be collected, and deep convolutional neural networks could be investigated for end-to-end sand foundry defect detection. Finally, the system should be integrated with a robotic removal station to enable fully automated post-processing of defective parts.
