ABSTRACT
Rail surface cracks may develop into rolling-contact-fatigue damage and contribute to rail fracture. This study focuses on one defect type: visible, elongated, groove-like cracks on the railhead running surface; internal flaws, squats, spalling and corrugation are outside its scope. A webcam-based machine-vision prototype is presented that combines a mechanically fixed camera, railhead region-of-interest processing, image enhancement, handcrafted descriptors and Random Forest classification. Images were resized to 640 × 480 pixels and analyzed in 32 × 32 pixel windows using Local Binary Pattern, Canny edge and Gabor features. On a dataset of 819 rail-surface images (401 crack and 418 normal or noise images), Random Forest achieved 76.77% accuracy and an AUC-ROC of 0.85 with a 30% test split, outperforming SVM and KNN baselines using the same features. The prototype integrates a C# WinForms interface, Python processing, MySQL logging and automatic storage of crack images. A ten-sample caliper check gave mean relative errors of 2.93% for length and 18.29% for width. The results support laboratory screening and inspection documentation, while image-level validation and field testing remain necessary.
Keywords:
Rail surface crack; Machine vision; Mechanical inspection prototype; Random Forest; Image database
1. INTRODUCTION
Railways are strategic transportation systems because they provide large carrying capacity, low unit transportation cost and stable long-distance operation. The safety of this infrastructure, however, strongly depends on the condition of the rail. The railhead is exposed to repeated wheel-rail contact, contact fatigue, impact loading, abrasive wear, oxidation and corrosion. Surface cracks are particularly important because they are directly visible symptoms of material discontinuity and may indicate the initiation or growth of deeper damage. If crack evolution is not detected in time, local surface defects can develop into more severe degradation, reduced load-bearing capacity and, in extreme cases, rail fracture.
Traditional rail inspection combines visual patrols and nondestructive testing methods. Ultrasonic testing, eddy-current testing, magnetic flux leakage, guided waves and laser ultrasonic methods are effective for several classes of defects, especially when internal or near-surface discontinuities must be investigated. Nevertheless, manual visual inspection remains widely used for surface-visible defects because it is simple and low cost. Its limitations are also clear: results depend on inspector experience, fatigue, lighting condition, access to the rail, and subjective interpretation of crack severity. A railway network with long track length requires inspection solutions that are faster, more reproducible and easier to digitize than purely manual observation.
Machine vision has therefore become an important complementary technology for railway maintenance. The basic principle is to acquire rail-surface images and use image analysis or learning algorithms to detect abnormal patterns such as head checks, squats, spalling, shelling, corrosion pits and crack-like grooves. Machine-vision inspection is noncontact, it can preserve image evidence, and it can support data-driven maintenance by storing the inspection history. Recent reviews and datasets emphasize that railway inspection research is moving from visual assessment toward automated image interpretation, with attention to nondestructive testing, dataset construction, reliability, real-time operation and field deployment [1,2,3].
Vision-based rail surface inspection has been studied for more than a decade. Early systems relied on image enhancement and hand-designed decision rules; for example, LI and REN [4] proposed a real-time visual inspection system for discrete surface defects of rail heads, and GAN et al. [5] developed a hierarchical extractor-based visual rail surface inspection system. Focusing specifically on cracks, ZHUANG et al. [6] proposed a double-layer data-driven framework for the automated vision inspection of rail surface cracks, showing that crack detection benefits from a dedicated pipeline rather than from a generic defect detector. Deep convolutional neural networks were applied to rail surface defect detection by FAGHIH-ROOHI et al. [7], and ZHUANG et al. [8] later presented a deep-learning-powered framework for the automatic identification of multiple rail-surface flaws. More recently, WANG et al. [9] proposed a hierarchical transfer-generative framework that automates several analytical tasks in rail surface defect inspection. Together, these studies show a clear progression from rule-based processing to data-driven and multi-task inspection.
Recent rail-surface studies show the high potential of deep learning. CHOI and HAN [10] used Fast R-CNN to evaluate rail surface defects and reported a mean average precision of 94.9%, which is a strong benchmark for deep-learning-based rail inspection. Other recent studies have improved one-stage and feature-fusion detectors for rail surface defects, including CenterNet-based approaches and dual-path feature fusion [11, 12]. Additional machine-vision and transfer-learning studies for railway faults further demonstrate that specialized visual models can improve the speed-accuracy tradeoff in practical inspection [13, 14]. These studies define the current research frontier, but they generally require a larger annotated dataset, more complex model training and, in many cases, GPU-supported computation.
The present paper addresses a narrower engineering question. It targets a single defect type, namely visible, elongated, groove-like cracks on the railhead running surface, and asks how far a webcam-based, CPU-oriented inspection prototype can be developed when the available dataset is still limited and when the system must include not only classification but also mechanical stabilization, an image database, a user interface and inspection logging. This question is relevant for education laboratories, early-stage engineering prototypes and resource-constrained railway maintenance contexts where a high-end inspection car is not immediately available. In such contexts, classical image descriptors remain useful because they are interpretable and computationally light. Local Binary Patterns (LBP) capture local texture differences, Canny detects crack boundaries, and Gabor filters represent oriented line-like patterns. These features correspond to physical characteristics of rail cracks: contrast difference, edge discontinuity and directional morphology.
Another motivation is the broader relevance of image-based inspection in materials and infrastructure applications. Recent studies have used machine learning, deep learning and image processing for crack detection, concrete-crack analysis, metallic-alloy identification and surface-defect grading [15,16,17]. Other works have further confirmed that image processing and machine learning are accepted methodological directions for material-surface inspection [18,19,20]. These publications show that a contribution is stronger when it is not limited to an algorithmic accuracy number but also explains data preparation, feature selection, model comparison, interpretation of errors and practical integration. Therefore, this paper emphasizes the system-level contributions of the developed prototype, including the mechanical inspection structure, rail-surface image database, software interface and inspection-data logging function.
The main contributions of this work are as follows. First, the authors designed a mechanical camera support and inspection arrangement to maintain a stable observation distance between the webcam and the rail surface. Second, a local rail-surface image database was built, including crack, normal and confusing-noise images such as rust, scratches and reflections. Third, the image-processing and machine-learning workflow is formulated using reproducible mathematical expressions and step-by-step pseudocode for LBP, Gabor filtering, Random Forest decision aggregation, calibration and evaluation metrics. Fourth, the prototype integrates Python image processing with a C# WinForms interface and MySQL logging, so that the operator can see crack location, dimensions, stored image path and historical inspection records. Fifth, the results are discussed against recent rail-defect detection and image-based materials-inspection studies to clarify the current value and limitations of the prototype.
The remainder of the paper is organized as follows. The Materials and Methods section first defines the inspection problem and its scope and describes the rail-surface image dataset; it then presents the proposed detection method, including preprocessing, feature extraction, classification, algorithm pseudocode and calibration, and finally describes the experimental platform (mechanical prototype and software) and the evaluation protocol. The Results section reports the classification performance, real-time operation, traceability functions and an auxiliary crack-size estimation check. The Discussion section compares the prototype with related studies and outlines its limitations, and the Conclusions section summarizes the main findings.
2. MATERIALS AND METHODS
2.1. Problem definition and scope
Rail surface defects form a broad family that includes head checks, squats, spalling, shelling, corrugation, wear, corrosion pits and crack-like grooves, and several of them have subsurface components that can only be assessed by nondestructive testing [1, 2]. This study does not attempt to address all of these defect types. Its target is a single, well-defined class: visible, elongated, groove-like cracks on the running surface of the railhead that appear as narrow dark discontinuities in a two-dimensional intensity image acquired from above the rail. The crack samples used in the size-estimation check have lengths of 23–69 mm and a nominal width of 1.75 mm (Section 3.6), which is within the resolving capability of the webcam at the fixed observation distance.
The task is formulated as a binary local-window classification problem: each 32 × 32 pixel window of the processed rail image is assigned either to the crack class or to the non-crack class. The non-crack class deliberately includes surface conditions that resemble cracks in intensity images, namely rust, scratches, nonuniform illumination and specular reflection, because these are the main sources of false alarms in practice. Internal and subsurface flaws, squats, spalling, shelling, corrugation and wear are outside the scope of the present prototype; they require other sensing principles or dedicated multi-class models, such as those reviewed in [1, 2] or proposed in [8, 9]. For windows classified as cracks, an auxiliary module estimates the crack length, width and area for inspection documentation; this module is not intended as certified metrology.
2.2. Rail-surface image dataset
A rail-surface database was created to train and evaluate the classifier. The experimental dataset contains 819 original images, including 401 images belonging to the crack class and 418 images corresponding to normal or confusing surface conditions. The normal/noise group includes rail surface patterns that may be mistaken for cracks, such as rust, scratches, nonuniform illumination and local reflection. This is important because a practical inspection model must distinguish actual crack-like discontinuities from harmless texture variations.
The input images are resized to 640 × 480 pixels, and the analysis is performed on 32 × 32 pixel local windows. Local-window classification is useful for small defects because the crack may occupy only a limited area of the full frame. It also increases the number of training samples from a limited number of original images. Because adjacent windows from the same image are correlated, the reported values are interpreted as prototype-level local-window performance rather than independent field-level generalization. Independent image-level separation and field-level validation are identified as the next step for reducing data-leakage risk in future experiments.
Table 1 summarizes the dataset and acquisition settings used in the prototype evaluation. Future releases of the dataset should also include the rail type, detailed crack morphology and acquisition metadata to support broader reproducibility.
2.3. Proposed detection method
2.3.1. Overall workflow of the proposed system
The proposed system was designed as an integrated inspection prototype rather than as a stand-alone classifier. The architecture includes five functional layers: mechanical arrangement, image acquisition, image-processing and feature extraction, machine-learning classification, and operator-level data management. This structure is important because rail inspection requires repeatable imaging, fast feedback and traceable results. An algorithm that cannot be connected to a camera, a display and a data record has limited direct value for maintenance personnel.
The mechanical layer (Section 2.4.1) fixes the camera relative to the rail sample and reduces image variation caused by hand motion or changing angle. The acquisition layer uses a USB webcam to capture railhead images. The processing layer performs ROI selection, grayscale conversion, background suppression, contrast enhancement, morphology and feature extraction. The machine-learning layer applies Random Forest classification to local image windows. The application layer displays the results on a C# WinForms interface and stores the inspection events in a MySQL database (Section 2.4.2). Figure 1 presents the complete methodological workflow and the way in which the proposed prototype converts a rail-surface image into a detection, measurement and data-management result.
Proposed rail surface crack detection workflow, from image enhancement to handcrafted feature fusion, Random Forest classification, measurement and data management.
As shown in Figure 1, the system is organized as a continuous inspection chain rather than as an isolated classifier: it begins with a raw rail-surface image and ends with a measured and stored defect record. This organization is important for rail inspection because the same pipeline must handle surface reflectance, rust-like noise, crack-like grooves and the need for traceable maintenance data.
First, the input frame is converted to grayscale and stabilized by median filtering, background flattening and CLAHE. These operations reduce random noise, compensate for nonuniform illumination and increase the local contrast of dark groove-like structures. The enhanced image is then processed by black-hat morphology, opening and closing. In this stage, the objective is to emphasize narrow dark discontinuities while suppressing small isolated particles or roughness that may appear on oxidized rail surfaces.
After image enhancement, the workflow extracts three complementary descriptors. LBP represents local texture variations caused by rust, scratches and surface roughness; Canny emphasizes abrupt intensity transitions along crack boundaries; and Gabor filters highlight oriented line-like responses associated with groove-shaped defects. The resulting descriptors are fused into a feature vector and passed to the Random Forest classifier. A positive crack decision can activate an auxiliary pixel-to-millimeter conversion module to estimate crack length, width and area for documentation, whereas normal or rust-noise regions are rejected or recorded as noncritical observations. Finally, the result is displayed on the WinForms interface and stored in MySQL, connecting the vision algorithm to practical inspection documentation.
2.3.2. Pre-processing and ROI extraction
Rail images are affected by nonuniform illumination, metallic reflection, surface roughness and rust. The preprocessing stage was designed to reduce these disturbances before feature extraction. The raw image is converted to grayscale, smoothed by median filtering, corrected by background suppression and enhanced by CLAHE. These operations follow common digital-image-processing principles and the local contrast enhancement strategy used in CLAHE-based image improvement [21, 22].
In the morphological enhancement stage, the structuring element B is used to define opening, closing and black-hat transformation as follows:
Here, the symbols ⊖ and ⊕ denote erosion and dilation, respectively. These operations suppress weak background variations and emphasize dark groove-like regions that may correspond to rail-surface cracks.
The ROI is selected around the railhead. This step is necessary because the full image may include the experimental frame, side areas, background, ballast or irrelevant mechanical elements. ROI restriction improves detection speed and reduces false alarms. In future experiments, the ROI should be automatically derived from the rail boundary or manually fixed after camera calibration. The current prototype uses a central processing area adapted to the mechanical setup.
Figure 2 illustrates the preprocessing effect using images from the experimental prototype. Background suppression and local contrast enhancement make the dark crack-like grooves more visible, while morphological processing reduces weak random texture. This justifies the use of handcrafted descriptors because the preprocessing stage explicitly improves the physical contrast between rail background and crack candidates.
2.3.3. Feature extraction
The feature vector combines texture, edge and directional information. Let I(x,y) denote the grayscale intensity at pixel (x,y). The LBP code of a center pixel c is computed by comparing its gray level with those of P neighboring pixels located on a circle of radius R:
where the binary threshold function is defined as:
In this study, the LBP descriptor is used because rail cracks appear as local intensity discontinuities relative to their neighborhood; this use is consistent with the texture-classification role of rotation-invariant local binary patterns [23].
For edge information, the Canny process estimates the image gradients G_x and G_y. The gradient magnitude and direction are represented as:
Non-maximum suppression and thresholding retain significant local boundaries. Canny edges are relevant because a crack generally creates an abrupt gray-level transition along its boundary [24].
For directional texture, a two-dimensional Gabor kernel can be written as:
where the rotated coordinates are:
Gabor filters are suitable for rail-surface cracks because they respond to oriented texture and spatial-frequency patterns, which are important for elongated dark grooves [25, 26].
The complete feature vector is obtained by concatenating LBP texture statistics, Canny edge indicators and Gabor responses. The physical interpretation is straightforward: a crack should have local texture contrast, edge discontinuity and oriented line-like structure. Figures 3 and 4 present examples of the LBP and Gabor feature maps generated by the prototype image-processing pipeline.
Feature extraction example showing the original image and LBP-based texture representation.
2.3.4. Random Forest classifier and baseline models
Random Forest was selected as the main model because it can learn nonlinear interactions among heterogeneous handcrafted descriptors and is less sensitive to individual noisy features than a single decision tree. Let h_t(x) be the prediction of the t-th tree for feature vector x. The ensemble prediction is obtained by majority voting over T trees:
Random Forest is a robust choice for mixed texture, edge and orientation descriptors, and its hyperparameters are reported here following common tuning practice [27, 28].
Two baseline models were used for comparison. The SVM model used an RBF kernel with C = 10 and gamma = scale. The RBF kernel is expressed as:
This model is appropriate when the boundary between crack and non-crack feature vectors is nonlinear. The KNN model with k = 5 was used as a distance-based baseline, where the predicted class is obtained from the majority label among the k nearest samples:
These two baselines represent widely used supervised-learning approaches for nonlinear classification and nearest-neighbor pattern recognition [29, 30].
The adopted Random Forest configuration included n_estimators = 300, min_samples_leaf = 2 and max_depth = None. This configuration was used as the main classical baseline in the present prototype evaluation. Repeated-seed validation and extended hyperparameter optimization will be considered in future work to further quantify statistical robustness (Figure 5).
2.3.5. Algorithm implementation and pseudocode
To make the execution of the method reproducible, the complete procedure is summarized as pseudocode. Algorithm 1 describes the offline stage, in which local windows are extracted from the labelled images, feature vectors are computed and the classifiers are trained and evaluated. Algorithm 2 describes the online inspection stage executed for each camera frame, including window classification, crack-region extraction, size estimation and database logging. The parameter values used in both stages are listed in Table 2.
2.3.6. Physical measurement and calibration
After a crack candidate is detected, its pixel dimensions are converted to millimetres. If k denotes the calibration factor in mm/pixel, the bounding-box length and width are converted as:
The corresponding area can be approximated as:
where A_px is the pixel area of the segmented contour or bounding rectangle. This calculation is simple, but its accuracy depends strongly on camera perspective, pixel resolution and boundary extraction.
For this reason, the physical measurement component must be separated from the binary detection component. The classifier may correctly identify a crack region, while the measured width may still be affected by boundary thresholding when the crack is only a few pixels wide. Calibration should therefore be reported together with mean relative error, error range and repeatability indicators for length and width. In the present prototype, the caliper-checked measurement results are treated as a limited preliminary verification of the size-estimation function, not as certified metrological validation.
2.4. Experimental platform
This section describes the hardware and software platform that was used to acquire the rail images and to execute the method described in Section 2.3 in real time.
2.4.1. Mechanical inspection prototype
The mechanical structure is one of the practical contributions of this work. It was implemented after the algorithm and software had been designed, so that the image-processing workflow could be tested under a repeatable observation geometry. Its purpose is to hold the camera above the rail surface and maintain the observation geometry during image acquisition. A stable structure improves repeatability by reducing motion blur, perspective variation and uncontrolled changes in the size of the railhead in the image.
The experimental setup uses a webcam mounted on a frame, with the rail sample located below the camera. The support is simple, modular and suitable for laboratory tests. The camera position was selected so that the railhead surface occupies the central region of the image. This is consistent with the ROI strategy in the software. Because rail-surface cracks are narrow and width estimation is sensitive to pixel resolution, the mechanical distance, camera tilt and illumination condition must be carefully controlled when the prototype is used for quantitative sizing.
Figure 6 shows the mechanical prototype and the camera arrangement. The fixed frame provides repeatable image acquisition for laboratory validation and supports a consistent railhead ROI. The same arrangement can be extended in future work with calibrated illumination or an inspection trolley, but the current setup is adequate for evaluating the proposed image-processing and classification workflow.
2.4.2. Software interface, image storage and MySQL database
The software interface is another contribution of this work. The GUI was developed using C# WinForms and communicates with the Python image-processing module. The interface contains camera control, live display, detection results, crack dimension fields and a log table. This design is intended for practical inspection: an operator can start the camera, observe the live rail image, see the detected crack region and inspect the stored measurement records without interacting directly with the Python code.
The MySQL database stores each crack detection event. The implemented cracklog table includes fields such as id, detection time, defect type, length, width, area and image path. This table is a useful basis for digitized rail inspection history. Manual patrol records are often subjective and difficult to analyze statistically; in contrast, a database log enables later filtering, counting, trend analysis and evidence retrieval. Figure 7 shows the GUI, and Table 3 lists the main fields of the cracklog table.
For future field implementation, the database module can be extended with stress testing, including records written per minute, average insertion time and continuous-camera operation. If the prototype is later mounted on an inspection trolley, GPS or rail-position metadata can also be added to each detection record.
2.5. Evaluation protocol and metrics
The local windows extracted from the 819 images were randomly divided into training and test subsets using test ratios of 20%, 30% and 40%, and the three classifiers were trained and tested on the same feature representation. Classification performance was evaluated using confusion matrix, accuracy, precision, recall, F1-score and AUC-ROC. For a binary crack detection task, TP denotes crack windows correctly classified as crack, TN denotes normal windows correctly classified as normal, FP denotes normal/noise windows falsely classified as crack, and FN denotes crack windows missed by the classifier. These metrics are standard for supervised classification and are suitable for balancing detection reliability and false-alarm risk [31].
The evaluation metrics are computed as:
In rail inspection, recall is safety-critical because it measures the fraction of actual crack samples that are detected. Precision is also important because excessive false alarms increase operator workload. F1-score balances these two metrics, while AUC-ROC evaluates the ranking ability of the model over different thresholds. Measurement error is calculated as:
where V_actual and V_software denote the manually measured value and the value displayed by the software, respectively.
3. RESULTS
3.1. Dataset balance and practical meaning
The image database is nearly balanced at the original-image level: 401 crack images and 418 normal/noise images. This balance is useful because accuracy is less likely to be dominated by one class. However, the local-window representation creates a much larger number of samples, and the final distribution depends on how windows are extracted and labelled. The best Random Forest evaluation used a test support of 73,530 local samples, with 37,440 normal samples and 36,090 crack samples in the classification report. To avoid overinterpreting the result, the reported metrics are treated as local-window prototype performance rather than independent field-level generalization.
The dataset includes confusing background patterns. This is important because rail surface inspection is not a clean binary image task. Rust, scratches, shadows and reflections often create dark or edge-rich patterns that resemble cracks. The reported false positives should therefore be interpreted as a symptom of a realistic surface-noise problem rather than only as model weakness. Expanding the non-crack class with more rust, scratch and oil-stain images is expected to reduce false alarms.
3.2. Confusion matrix, ROC curve and metric interpretation
Figure 8 shows the confusion matrix and ROC curve obtained in the local-window evaluation. Interpreting the crack class as the positive class, the matrix gives TN = 28,024, FP = 9,416, FN = 7,665 and TP = 28,425. These values lead to 76.77% total accuracy. More importantly, the crack-class recall is approximately 0.79 and the crack-class precision is approximately 0.75, consistent with the classification report in Table 4.
Classification report of the best Random Forest model (n_estimators = 300, min_samples_leaf = 2, max_depth = None; 30% test split; AUC-ROC = 0.85).
The recall being higher than precision has a practical implication. In a safety-oriented screening tool, missing cracks is usually more serious than creating additional candidate regions for operator review. Therefore, a model with relatively high recall can be acceptable in an early screening prototype. However, if the software is deployed for continuous inspection over long rail lengths, false positives may become a practical burden. The final system should therefore allow threshold tuning to select an operating point according to the inspection objective.
The AUC-ROC value of 0.85 is an important result because it is less dependent on a single threshold than accuracy. It indicates that the feature vector has meaningful discriminative capacity for ranking crack-like and non-crack windows. This result supports the scientific value of combining texture, edge and directional descriptors. Nevertheless, AUC alone is not enough for rail safety, and the next stage must add image-level metrics, object-level localization metrics and independent field validation.
3.3. Comparison among Random Forest, SVM and KNN
The three classifiers were evaluated under three test-set ratios. Random Forest achieved the highest accuracy in all cases: 75.96% for 20% test data, 76.77% for 30% test data and 75.79% for 40% test data. SVM was consistently close but slightly lower, ranging from 74.90% to 75.47%. KNN remained the weakest model, with accuracy around 73%.
The small but consistent advantage of Random Forest is meaningful because all models used the same feature representation. It indicates that tree ensembles are better suited to the nonlinear combination of LBP histograms, edge indicators and Gabor orientation responses. KNN is more sensitive to local noise and feature scaling, which is problematic when rail images contain rust and reflection. SVM performs reasonably well but may not exploit local feature interactions as flexibly as an ensemble of decision trees.
Statistical reliability can be strengthened in future experiments by adding repeated runs with different random seeds or stratified image-level cross-validation. Confidence intervals or bootstrap analysis would further support the comparison among Random Forest, SVM and KNN. In the present study, the comparison is interpreted as a prototype-level model-selection result under the reported dataset and feature configuration (Figure 9, Table 5).
3.4. Real-time operation and software output
The system operated at approximately 20–30 FPS on a common computer without a dedicated GPU. This is an important engineering result because many high-performance deep-learning systems are difficult to deploy on ordinary CPU hardware. The classical feature pipeline has lower computational complexity and can therefore provide live feedback to the operator. The interface displays the original video frame, detected crack region, estimated dimensions and the log table.
Figure 7 (Section 2.4.2) shows an example of real-time detection on the laboratory prototype, and Figure 10 shows crack detection on a real rail surface. These figures demonstrate that the software pipeline is not only an offline training script; it has been connected to a working GUI and image-storage routine. The visualization layer improves usability because the operator can verify whether the detected region corresponds to a real crack-like feature.
For deployment-oriented characterization, the FPS result should be complemented with average processing time per frame, standard deviation, CPU model, memory usage, camera frame rate and resolution. Tests under different ROI sizes would also be useful because the number of local windows strongly affects processing time.
3.5. Crack image storage and inspection traceability
A practical inspection system should preserve evidence. The prototype stores images of detected cracks in a local folder and records metadata in MySQL. Figure 11 shows the saved crack images. This contribution is important for railway maintenance because it supports later review, comparison over time and creation of a larger annotated dataset. Each new inspection event can become additional training or validation data after expert verification.
Traceability also improves the scientific value of the experiment. If stored images are linked to the model output, database record and physical measurement, errors can be audited. For example, false positives can be grouped by cause, such as rust, reflection or scratch. False negatives can be analyzed to determine whether the crack was too thin, too low contrast or outside the ROI. This feedback loop is necessary for iterative improvement of the system.
3.6. Auxiliary preliminary crack-size estimation assessment
The prototype was evaluated for auxiliary preliminary crack-size estimation by comparing the software-displayed dimensions with values measured by a mechanical caliper. Table 6 summarizes the ten-sample results. The experiment should be interpreted as a feasibility check under controlled laboratory geometry because the tested cracks covered a limited range of lengths and a constant nominal width. Within this scope, the relative length error ranged from 0.15% to 7.83%, with a mean value of 2.93%, indicating that length estimation can provide useful indicative documentation for visible, elongated cracks.
Auxiliary preliminary crack-size estimation assessment comparing software output with caliper measurements.
Width estimation remained more sensitive than length estimation. The relative width error ranged from 14.29% to 20.00%, with a mean value of 18.29%. This result is technically reasonable because the actual width was only 1.75 mm for all samples; at this scale, small boundary shifts in the segmented crack region can noticeably change the relative error. Therefore, the width values are reported only as preliminary indicators of the prototype sizing function, whereas length is the more stable measurement output in the current dataset.
Figure 12 compares the relative length and width errors sample by sample. The graph shows that the width curve is consistently higher than the length curve, confirming that crack-width estimation is the more demanding task. For this reason, comparisons with related studies are made mainly in terms of crack detection, screening and documentation performance, while the size-estimation result is treated as an auxiliary function that can be improved by higher optical resolution, perspective correction, sub-pixel edge localization and calibration over a broader range of crack widths and lengths.
Relative-error comparison for the auxiliary preliminary crack-length and crack-width estimation test.
4. DISCUSSION
4.1. Scientific interpretation of the reported results
The obtained accuracy of 76.77% should be interpreted carefully. It is not competitive with state-of-the-art deep-learning systems trained on larger datasets, but it is meaningful for a webcam-based prototype using handcrafted features and CPU operation. The result demonstrates that rail-surface cracks generate enough texture, edge and orientation cues to be separated from many normal/noise windows. The AUC of 0.85 further confirms that the feature vector has useful ranking ability.
The main strength of the method is system integration. Instead of stopping at an offline classification result, this work includes a mechanical camera arrangement, a surface-image database, a real-time interface, a data-storage design and an auxiliary size-estimation module. These components make the work closer to an engineering inspection device. The practical integration is therefore presented as the central contribution, while the moderate classification accuracy is interpreted as a baseline for further development.
The result also suggests that the current feature extraction pipeline is better at detecting visible, elongated and high-contrast crack-like grooves than at performing high-precision boundary metrology. This is consistent with the limited measurement assessment: length estimation remains more stable than width estimation because length follows the main crack direction, whereas width depends on the exact boundary of a very thin object. Therefore, the prototype is positioned as an automatic screening and documentation tool with indicative, auxiliary size-estimation capability.
4.2. Comparison with rail surface defect studies
Compared with CHOI and HAN [10], who reported 94.9% mAP for Fast R-CNN on rail surface defects, the present Random Forest result is clearly lower. The reason is not only the classifier type. Deep-learning object detectors learn hierarchical features directly from images and can optimize localization and classification jointly. The present work uses manually designed descriptors and local-window classification, which limits the representation capacity. However, the present system has a lower computational requirement and is easier to run on a common laptop.
Recent rail-surface defect studies based on improved CenterNet, dual-path feature fusion and other railway machine-vision variants show that the field is moving toward specialized deep-learning architectures [11,12,13]. Transfer-learning and YOLO-based railway-fault studies also support this trend toward more expressive detectors [14]. These models are more suitable for high-accuracy deployment when a large labelled dataset and GPU training environment are available. The current prototype provides a different baseline: it clarifies what can be achieved with webcam-based acquisition, CPU operation, handcrafted descriptors and simple integration. This baseline is useful before investing in a large deep-learning pipeline because it identifies the main error modes: false alarms caused by rust/reflection and width-estimation uncertainty.
The comparison with crack-focused rail studies is also informative. The double-layer framework of ZHUANG et al. [6] and the multi-flaw framework of ZHUANG et al. [8] demonstrate that dedicated, data-driven pipelines can automate rail-surface crack and flaw identification, and WANG et al. [9] showed that a hierarchical transfer-generative framework can support several inspection tasks within one system. In contrast with these studies, the present work restricts the target to visible railhead surface cracks and places the emphasis on a low-cost, CPU-based, mechanically integrated prototype with traceable data logging. The present results should therefore be read as a baseline for this narrower problem rather than as a competing multi-defect solution.
The comparison also suggests a direct development path. The current mechanical fixture and image database can be preserved, while the classifier can be upgraded to a lightweight deep-learning model such as YOLOv8n, MobileNet-based detector or small segmentation network. The WinForms interface and MySQL logging do not need to be redesigned; only the detection core would change. This modularity is a practical contribution of the system architecture.
4.3. Comparison with image-processing studies in materials inspection
The selected related studies show that image processing and machine learning are widely used methodological directions in materials inspection. HE et al. [15] proposed a lightweight YOLOv8-SD model for stone slab crack detection, while TAJ et al. [16] compared CNN, SVM and KNN for precision crack analysis in concrete structures. PADMAPOORANI and SENTHILKUMAR [17] used CNN architecture for concrete crack detection, and PEREIRA JUNIOR et al. [18] reported very high accuracy for deep neural networks on a large concrete crack dataset. Other studies used image processing and machine learning for metallic-alloy identification and textile pilling grading [19, 20].
These studies provide two lessons for the present paper. First, high accuracy is possible when the dataset is large, well labelled and the model is sufficiently expressive. Second, a strong paper must demonstrate more than a numerical score: it must describe image acquisition, preprocessing, metrics, comparison models and practical significance. Accordingly, the present study documents the mechanical structure, database design, mathematical formulation, pseudocode and interface integration in addition to the classification scores.
The rail application is more challenging than many static laboratory crack datasets because rail surfaces can be shiny, rusted, dirty and geometrically curved. The class boundary between cracks and non-crack dark marks is also less clear. Therefore, the moderate accuracy in the current rail prototype should be interpreted as an engineering baseline that motivates dataset expansion, calibration improvement and field validation.
4.4. Why Random Forest performed better than SVM and KNN
The feature vector combines descriptors with different meanings and statistical distributions. LBP features summarize texture; Canny features emphasize boundaries; Gabor features respond to orientations and frequencies. Random Forest can select useful thresholds across these heterogeneous dimensions and combine them through ensemble voting. This explains why it performed consistently better than SVM and KNN.
SVM with an RBF kernel can model nonlinear separation, but its performance depends on feature scaling and hyperparameter tuning. With a limited dataset and mixed descriptors, the chosen C and gamma values may not fully capture local variations. KNN is more vulnerable because distance in high-dimensional feature space may not reflect semantic similarity when rust or reflection changes the feature values. This explains why KNN remained lower than the other models.
The performance gap among the three methods is not very large. Therefore, the conclusion is intentionally limited in scope: for this dataset, feature representation and parameter setting, Random Forest was the most stable classical baseline.
4.5. Limitations and future work
The current prototype has several limitations that define the scope of the reported results. The dataset is still relatively small and the laboratory cracks are more regular than many natural rail defects. In addition, the study addresses only one defect type; extending the method to other rail-surface defects would require multi-class labels and possibly different descriptors. In addition, local-window evaluation is useful for algorithm development, but independent image-level and field-level validation should be conducted before safety-critical deployment. The crack-size experiment also covers only a limited range of crack lengths and a single nominal width. Accordingly, the reported size-estimation result should be interpreted as a feasibility check of the auxiliary sizing function rather than as full metrological validation.
Future work will focus on expanding the dataset with natural rail defects, improving illumination control, repeating training under fixed image-level splits, comparing the Random Forest baseline with lightweight deep-learning detectors, and refining calibration for width and area estimation. In the measurement component, future experiments should include a broader range of crack widths and lengths, repeated acquisition at different camera distances, and repeatability analysis under controlled illumination.
Table 7 summarizes the comparison with related work and clarifies the position of the proposed prototype relative to recent deep-learning and image-based materials-inspection studies.
5. CONCLUSIONS
This study demonstrated a vision-based prototype for the detection of visible, elongated cracks on the railhead running surface. The work combines a mechanical camera fixture, USB webcam acquisition, a rail-surface image database, preprocessing, LBP/Canny/Gabor features, Random Forest classification, WinForms visualization, MySQL logging and image storage. These components form an integrated inspection prototype rather than a stand-alone classification experiment.
On the reported dataset of 819 images, Random Forest achieved 76.77% accuracy and AUC-ROC = 0.85 under the local-window prototype evaluation with a 30% test split, outperforming SVM and KNN baselines under the same handcrafted feature representation. The crack-class recall of about 0.79 suggests useful safety-oriented screening capability, while the precision of about 0.75 indicates that false positives remain significant. Real-time operation at approximately 20–30 FPS on CPU hardware supports the feasibility of deployment on ordinary computers.
The auxiliary preliminary crack-size estimation assessment showed that crack-length estimation was more stable than crack-width estimation in the limited ten-sample caliper check. The mean relative length error was 2.93%, while the mean relative width error was 18.29%. This difference is technically reasonable because width is strongly influenced by pixel-level boundary uncertainty for narrow cracks. The current system should therefore be positioned as a detection, screening and documentation tool with indicative size information, rather than as a certified metrological instrument.
Compared with recent deep-learning rail-defect studies, the current method has lower accuracy but offers lower computational cost, easier interpretation and a complete hardware-software prototype. The next research stage should expand natural crack images, improve calibration over broader crack-size ranges, repeat statistical testing and compare the current baseline with lightweight deep-learning detectors to move the prototype toward field-ready rail inspection.
6. ACKNOWLEDGMENTS
The authors acknowledge the University of Transport and Communications for supporting the experimental prototype and project development. This research is funded by the Ministry of Education and Training under grant number B2027-GHA-10.
7. DATA AVAILABILITY
The data supporting the findings of this study, including the rail-surface image dataset, the extracted feature data, the trained classification models and the crack-size measurement records, are available from the corresponding author, Dao Thanh Toan (daotoan@utc.edu.vn), upon reasonable request.
8. BIBLIOGRAPHY
-
[1] MORDIA, R., VERMA, A.K., “Nondestructive testing methods for rail defects detection”, High-speed Railway, v. 3, n. 2, pp. 163–173, Aug. 2025. doi: https://doi.org/10.1016/j.hspr.2025.03.001.
» https://doi.org/10.1016/j.hspr.2025.03.001 -
[2] KUMAR, A., HARSHA, S.P., “A systematic literature review of defect detection in railways using machine vision-based inspection methods”, International Journal of Transportation Science and Technology, v. 18, pp. 207–226, Jun. 2025. doi: https://doi.org/10.1016/j.ijtst.2024.06.006.
» https://doi.org/10.1016/j.ijtst.2024.06.006 -
[3] ARAIN, A., MEHRAN, S., SHAIKH, M.Z., et al, “Railway track surface faults dataset”, Data in Brief, v. 52, pp. 110050, Feb. 2024. doi: https://doi.org/10.1016/j.dib.2024.110050. PubMed PMID: 38299101.
» https://doi.org/10.1016/j.dib.2024.110050 -
[4] LI, Q., REN, S., “A real-time visual inspection system for discrete surface defects of rail heads”, IEEE Transactions on Instrumentation and Measurement, v. 61, n. 8, pp. 2189–2199, Aug. 2012. doi: https://doi.org/10.1109/TIM.2012.2184959.
» https://doi.org/10.1109/TIM.2012.2184959 -
[5] GAN, J., LI, Q., WANG, J., et al, “A hierarchical extractor-based visual rail surface inspection system”, IEEE Sensors Journal, v. 17, n. 23, pp. 7935–7944, Dec. 2017. doi: https://doi.org/10.1109/JSEN.2017.2761858.
» https://doi.org/10.1109/JSEN.2017.2761858 -
[6] ZHUANG, L., WANG, L., ZHANG, Z., et al, “Automated vision inspection of rail surface cracks: a double-layer data-driven framework”, Transportation Research Part C, Emerging Technologies, v. 92, pp. 258–277, Jul. 2018. doi: https://doi.org/10.1016/j.trc.2018.05.007.
» https://doi.org/10.1016/j.trc.2018.05.007 -
[7] FAGHIH-ROOHI, S., HAJIZADEH, S., NÚÑEZ, A., et al, “Deep convolutional neural networks for detection of rail surface defects”, In: Proceedings of the 2016 International Joint Conference on Neural Networks (IJCNN), pp. 2584–2589, Vancouver, Canada, Jul. 2016. doi: https://doi.org/10.1109/IJCNN.2016.7727522.
» https://doi.org/10.1109/IJCNN.2016.7727522 -
[8] ZHUANG, L., QI, H., ZHANG, Z., “The automatic rail surface multi-flaw identification based on a deep learning powered framework”, IEEE Transactions on Intelligent Transportation Systems, v. 23, n. 8, pp. 12133–12143, Aug. 2022. doi: https://doi.org/10.1109/TITS.2021.3109949.
» https://doi.org/10.1109/TITS.2021.3109949 -
[9] WANG, T., ZHANG, Z., TSUI, K.L., “A hierarchical transfer-generative framework for automating multianalytical tasks in rail surface defect inspection”, IEEE Internet of Things Journal, v. 11, n. 12, pp. 21513–21526, Jun. 2024. doi: https://doi.org/10.1109/JIOT.2024.3374751.
» https://doi.org/10.1109/JIOT.2024.3374751 -
[10] CHOI, J.Y., HAN, J.M., “Deep learning (Fast R-CNN)-based evaluation of rail surface defects”, Applied Sciences, v. 14, n. 5, pp. 1874, Feb. 2024. doi: https://doi.org/10.3390/app14051874.
» https://doi.org/10.3390/app14051874 -
[11] MAO, Y., ZHENG, S., LI, L., et al, “Research on rail surface defect detection based on improved CenterNet”, Electronics, v. 13, n. 17, pp. 3580, Sep. 2024. doi: https://doi.org/10.3390/electronics13173580.
» https://doi.org/10.3390/electronics13173580 -
[12] ZHONG, Y., CHEN, G., “Rail surface defect detection based on dual-path feature fusion”, Electronics, v. 13, n. 13, pp. 2564, Jun. 2024. doi: https://doi.org/10.3390/electronics13132564.
» https://doi.org/10.3390/electronics13132564 -
[13] BAI, T., GAO, J., YANG, J., et al, “A study on railway surface defects detection based on machine vision”, Entropy, v. 23, n. 11, pp. 1437, Oct. 2021. doi: https://doi.org/10.3390/e23111437. PubMed PMID: 34828135.
» https://doi.org/10.3390/e23111437 -
[14] RODRIGUEZ-ABREO, O., QUIROZ-JUAREZ, M.A., MACIAS-SOCARRAS, I., et al, “Automatic detection of railway faults using neural networks: a comparative study of transfer learning models and YOLOv11”, Infrastructures, v. 10, n. 1, pp. 3, Jan. 2025. doi: https://doi.org/10.3390/infrastructures10010003.
» https://doi.org/10.3390/infrastructures10010003 -
[15] HE, D., PENG, R., WANG, F., “YOLOv8-SD: an enhanced lightweight model for efficient stone slab crack detection”, Matéria, v. 30, e20250569, 2025. doi: https://doi.org/10.1590/1517-7076-rmat-2025-0569.
» https://doi.org/10.1590/1517-7076-rmat-2025-0569 -
[16] TAJ, M.N.A.B.G., ALRUWAIS, N., ALSHAHRANI, H.M., et al, “Precision crack analysis in concrete structures using CNN, SVM, and KNN: a machine learning approach”, Matéria, v. 29, n. 4, e20240551, 2024. doi: https://doi.org/10.1590/1517-7076-rmat-2024-0551.
» https://doi.org/10.1590/1517-7076-rmat-2024-0551 -
[17] PADMAPOORANI, P., SENTHILKUMAR, S., “Application of machine learning for crack detection on concrete structures using CNN architecture”, Matéria, v. 28, n. 1, e20230010, 2023. doi: https://doi.org/10.1590/1517-7076-rmat-2023-0010.
» https://doi.org/10.1590/1517-7076-rmat-2023-0010 -
[18] PEREIRA JUNIOR, W.M., SILVA, S.F., SILVA, A.R., et al, “Cracks detection in images of concrete structures using deep neural networks”, Matéria, v. 29, n. 4, e20240354, 2024. doi: https://doi.org/10.1590/1517-7076-rmat-2024-0354.
» https://doi.org/10.1590/1517-7076-rmat-2024-0354 -
[19] PANDIAN, I., ALRUWAIS, N., ALSHAHRANI, H.M., et al, “Optimized batch identification of metallic alloy materials for precision machining operations using machine learning and image processing techniques”, Matéria, v. 30, e20240866, 2025. doi: https://doi.org/10.1590/1517-7076-rmat-2024-0866.
» https://doi.org/10.1590/1517-7076-rmat-2024-0866 -
[20] SHELVARAJU, M.C., ALZABEN, N., MAASHI, M., et al, “Pilling analysis for textile grading of synthetic fibre material using image processing and machine learning techniques”, Matéria, v. 29, n. 1, e20230336, 2024. doi: https://doi.org/10.1590/1517-7076-rmat-2023-0336.
» https://doi.org/10.1590/1517-7076-rmat-2023-0336 - [21] GONZALEZ, R.C., WOODS, R.E., Digital image processing, 4 ed., New York, Pearson, 2018.
-
[22] REZA, A.M., “Realization of the contrast limited adaptive histogram equalization (CLAHE) for real-time image enhancement”, The Journal of VLSI Signal Processing, v. 38, n. 1, pp. 35–44, Aug. 2004. doi: https://doi.org/10.1023/B:VLSI.0000028532.53893.82.
» https://doi.org/10.1023/B:VLSI.0000028532.53893.82 -
[23] OJALA, T., PIETIKAINEN, M., MAENPAA, T., “Multiresolution gray-scale and rotation invariant texture classification with local binary patterns”, IEEE Transactions on Pattern Analysis and Machine Intelligence, v. 24, n. 7, pp. 971–987, Jul. 2002. doi: https://doi.org/10.1109/TPAMI.2002.1017623.
» https://doi.org/10.1109/TPAMI.2002.1017623 -
[24] CANNY, J., “A computational approach to edge detection”, IEEE Transactions on Pattern Analysis and Machine Intelligence, v. 8, n. 6, pp. 679–698, Nov. 1986. doi: https://doi.org/10.1109/TPAMI.1986.4767851. PubMed PMID: 21869365.
» https://doi.org/10.1109/TPAMI.1986.4767851 -
[25] DAUGMAN, J.G., “Uncertainty relation for resolution in space, spatial frequency, and orientation optimized by two-dimensional visual cortical filters”, Journal of the Optical Society of America. A, Optics and Image Science, v. 2, n. 7, pp. 1160–1169, Jul. 1985. doi: https://doi.org/10.1364/JOSAA.2.001160. PubMed PMID: 4020513.
» https://doi.org/10.1364/JOSAA.2.001160 -
[26] GRIGORESCU, S.E., PETKOV, N., KRUIZINGA, P., “Comparison of texture features based on Gabor filters”, IEEE Transactions on Image Processing, v. 11, n. 10, pp. 1160–1167, Oct. 2002. doi: https://doi.org/10.1109/TIP.2002.804262. PubMed PMID: 18249688.
» https://doi.org/10.1109/TIP.2002.804262 -
[27] BREIMAN, L., “Random forests”, Machine Learning, v. 45, n. 1, pp. 5–32, Oct. 2001. doi: https://doi.org/10.1023/A:1010933404324.
» https://doi.org/10.1023/A:1010933404324 -
[28] PROBST, P., WRIGHT, M.N., BOULESTEIX, A.L., “Hyperparameters and tuning strategies for random forest”, Wiley Interdisciplinary Reviews. Data Mining and Knowledge Discovery, v. 9, n. 3, e1301, May. 2019. doi: https://doi.org/10.1002/widm.1301.
» https://doi.org/10.1002/widm.1301 -
[29] CORTES, C., VAPNIK, V., “Support-vector networks”, Machine Learning, v. 20, n. 3, pp. 273–297, Sep. 1995. doi: https://doi.org/10.1023/A:1022627411411.
» https://doi.org/10.1023/A:1022627411411 -
[30] COVER, T., HART, P., “Nearest neighbor pattern classification”, IEEE Transactions on Information Theory, v. 13, n. 1, pp. 21–27, Jan. 1967. doi: https://doi.org/10.1109/TIT.1967.1053964.
» https://doi.org/10.1109/TIT.1967.1053964 -
[31] HASTIE, T., TIBSHIRANI, R., FRIEDMAN, J., The elements of statistical learning: data mining, inference, and prediction, 2 ed., New York, Springer, 2009. doi: https://doi.org/10.1007/978-0-387-84858-7.
» https://doi.org/10.1007/978-0-387-84858-7
























