Layered dynamic adaptive self-supervised mask method and system for casting surface defect detection
By using a hierarchical dynamic adaptive self-supervised mask method, the problem of insufficient defect perception capability in casting surface defect detection is solved, achieving high-precision industrial quality inspection, adapting to multi-scale defect detection, and improving the applicability and detection effect of the pre-trained model.
Patent Information
- Application Number
- CN202611312332.2
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-08-27
- Publication Date
- 2026-11-27
AI Technical Summary
In existing casting surface defect detection, self-supervised pre-trained models have insufficient defect perception capabilities due to static masking strategies, which cannot meet the high-precision quality inspection requirements of industrial production lines. In particular, the false negative rate is high in the detection of small defects, and the fixed masking rate cannot adapt to multi-scale defects. The masking logic does not match the hierarchical visual feature extraction rules of the visual Transformer, resulting in poor pre-training performance.
A hierarchical dynamic adaptive self-supervised masking method is adopted. By evaluating the defect-sensitive region of the casting image, using Transformer multi-level differential masking, dynamic mask probability control, and hard constraints on the defect region mask, combined with global spatial attention and gray-level gradient features, differential hierarchical mask probabilities are generated to protect the defect-sensitive region and remove redundant background textures, thus achieving three-dimensional linkage between defect scale, network layer, and training rounds.
It significantly reduces the false negative and false positive rates of surface defects in castings, improves the quality of unlabeled image pre-training, adapts to industrial small-sample quality inspection scenarios, enhances the model's ability to perceive minute defects, and conforms to the hierarchical visual perception mechanism of visual Transformer.
Smart Images

Figure CN123181333A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the fields of industrial visual inspection and artificial intelligence self-supervised learning technology, and more specifically to a hierarchical dynamic adaptive self-supervised mask method and system for detecting surface defects in castings. Background Technology
[0002] Masked Autoencoder (MAE) is the mainstream Transformer self-supervised pre-training paradigm in the field of industrial visual defect detection. It addresses the industry pain points of scarce labeled samples for casting surface defect detection, difficulty in identifying minute defects, and strong interference from the casting's own texture. MAE is widely used in the industry to perform self-supervised pre-training on unlabeled original images of castings. By masking image blocks and reconstructing missing regions, the model can autonomously learn the inherent visual features of the casting surface texture, defect edges, crack contours, sand holes, and pores, reducing the reliance of downstream defect detection tasks on manually labeled data.
[0003] Currently, the common masking strategies used in industry and academia mainly include: (1) using fixed random masks. For example, industrial casting inspection uses a 75% general mask ratio to randomly mask the patch tokens of the casting image without discrimination, without distinguishing the sensitive areas of surface defects, the background areas of the body texture, and the invalid edge areas of the casting; (2) using fixed window masks, which mask local image blocks by using continuous windows.
[0004] However, existing static, indiscriminate masking strategies, when combined with casting surface defect detection scenarios, suffer from three major industry-specific pain points. These directly lead to insufficient defect perception capabilities in pre-trained models, persistently high downstream false negative rates, and an inability to meet the high-precision quality inspection needs of industrial production lines. Specifically:
[0005] (1) Casting defects include small-scale defects such as tiny sand holes, fine cracks, and missing material at the edges. Random masks are likely to directly obscure the key image blocks where the defects are located, causing the model to be unable to learn core features such as defect edges and gray-scale abrupt changes throughout the process, resulting in a significant increase in the missed detection rate of tiny defects in downstream detection tasks. At the same time, the rough texture of the casting body is redundant background information, but it is retained in large quantities, resulting in extremely low feature learning efficiency. (2) The scale of casting defects is extremely wide. Point-like sand holes are small-scale features, long cracks are large-scale continuous features, and large-area slag inclusions are regional defects. A single fixed 75% mask rate cannot meet the feature learning requirements of defects of different scales. If the mask rate is too high, all defect features will be destroyed, and if the mask rate is too low, redundant background textures of the casting cannot be removed. (3) The shallow layer of the visual Transformer is responsible for capturing fine-grained local features such as casting edges, textures, and defect contours. The middle layer integrates defect context associations, and the high layer identifies the global shape and category of defects. The existing global consistent masking method will excessively mask the details of shallow defects, and the high-level global feature mask is insufficient, resulting in the model being insensitive to minor defects in castings and the layered feature extraction capability being completely wasted.
[0006] Furthermore, existing visual adaptive masking schemes rely solely on attention weights to simply adjust mask probabilities without considering the inherent distribution characteristics of casting defects, the grayscale properties of industrial images, and the multi-scale nature of defects for customized optimization. They also tend to exhibit mask region clustering, completely obscuring local defect areas of the casting, failing to address the problem of missing minute defects. Moreover, training gradient oscillations are significant in small-sample industrial data scenarios, resulting in poor generalization ability when transferring pre-trained models to casting detection tasks. Therefore, what those skilled in the art urgently need to solve is: how to overcome the problems of existing self-supervised static masking strategies for casting defect detection that easily destroy small defect features, fixed masking rates that cannot adapt to multi-scale casting defects, masking logic that does not match the hierarchical visual feature extraction rules of visual Transformer, and poor pre-training effects in industrial small sample scenarios. Summary of the Invention
[0007] In view of the above problems, this invention proposes a hierarchical dynamic adaptive self-supervised masking method and system for casting surface defect detection that overcomes or at least partially solves the above problems. Through casting image defect-sensitive region evaluation, Transformer multi-level differentiated masking, dynamic mask probability control adapted to defect scale, hard constraint of defect region masking, and joint loss for defect perception, an industrial-specific intelligent masking mechanism with three-dimensional linkage between defect scale, network level, and training rounds is achieved. While ensuring that the difficulty of MAE reconstruction remains unchanged, it forcibly protects the casting defect-sensitive key regions, removes redundant and rough background textures from the casting, conforms to the hierarchical visual perception mechanism of the visual Transformer, significantly improves the pre-training quality of unlabeled casting images, and reduces the false negative and false positive rates of various surface defects such as cracks, sand holes, porosity, inclusions, and material shortages in downstream applications. This method is suitable for small-sample casting quality inspection scenarios in industrial production lines.
[0008] To achieve the above objectives, the present invention adopts the following technical solution: A hierarchical dynamic adaptive self-supervised masking method for surface defect detection in castings includes the following steps: S1. Obtain the original image of the surface of the casting on the industrial production line and preprocess it. Divide the preprocessed casting image into image blocks. Embed an encoding in each image block and fuse it with the position encoding to form an input token sequence. S2. Combining the global spatial attention heatmap and image block grayscale gradient features, based on the defect sensitivity score of each image block token, all image block tokens are divided into three levels: defect sensitive core token, ordinary casting body texture token, and casting invalid background token. S3. Combine the proportion of defect-sensitive core tokens in the current casting image, the current training round of the model, and the proportion of invalid background tokens in the casting to dynamically calculate the global base mask rate, and determine the number of target mask tokens corresponding to the current training round based on the dynamic global base mask rate; S4. Based on the dynamic global base mask rate, and based on the hierarchical visual perception mechanism of the visual Transformer encoder, the dynamic global base mask rate is hierarchically adjusted to obtain differentiated hierarchical mask probabilities. S5. Combining the image block level and the differential level mask probability, and superimposing the forced mask-free constraint for defect areas, the global mask quantity constraint and the spatial discrete mask constraint, perform weighted sampling of mask positions to generate the final mask position set; S6. Input the token sequence of the casting image after dynamic masking into the ViT-MAE model to perform forward reconstruction of the missing image region, and combine the image reconstruction loss and the defect region attention retention loss to update the model parameters and dynamic mask parameters in reverse. After multiple rounds of iterative training, the pre-trained ViT-MAE model is obtained and transferred to the downstream casting defect detection, segmentation or classification model.
[0009] Preferably, the specific content of step S2 is as follows: The attention response of each image block token in the spatial dimension is calculated, and the grayscale gradient response of each image block is also calculated. The attention response and grayscale gradient response are normalized respectively, and the defect sensitivity score is calculated by weighted fusion. All image block tokens are sorted according to the defect sensitivity score. Based on the image block token ranking, defect sensitive core tokens, casting invalid background tokens and ordinary casting body texture tokens are divided to obtain a token level set containing the level identifier of each image block token.
[0010] Preferably, in step S3, the dynamic global base mask rate is specifically:
[0011] in, Preset an initial reference mask rate for the casting inspection scenario. The proportion of the current casting image defect-sensitive core token to all image block tokens. , These represent the minimum and maximum values of the proportion of defect-sensitive core tokens in each casting image in the dataset; For the current training round, This represents the total number of pre-training rounds for the model. α represents the proportion of invalid background tokens in the current casting image to all image block tokens; α, β, and γ are the weight coefficients corresponding to defect sensitivity, training round, and background redundancy, respectively. , ε represents the lower and upper bounds of the dynamic global base mask rate, and ε is a very small constant to prevent the denominator from being zero.
[0012] Preferably, in step S4, the visual Transformer encoder consists of multiple Transformer blocks, which are divided into shallow layer group, mid layer group and high layer group according to the network depth. The shallow layer group is responsible for capturing local detailed features, reducing masking probability, and fully preserving details such as tiny sand holes and fine cracks; the middle layer group is responsible for fusing defect context space associations and using standard baseline masking probability; the high layer group is responsible for global defect morphology discrimination and defect classification, increasing masking probability, and strengthening the model's ability to distinguish defects from normal casting surfaces; the masking probability of the shallow layer group < the masking probability of the middle layer group < the masking probability of the high layer group.
[0013] Preferably, the specific content of step S5 is as follows: S51. Execute mandatory mask-free constraint on defect regions, assign a mask sampling weight of 0 to defect-sensitive core tokens, assign a mask sampling weight of 1 to ordinary casting body texture tokens, and assign a mask sampling weight η greater than 1 to invalid casting background tokens. S52. Based on the differential hierarchical mask probability and the level sampling weight corresponding to each image block token, perform weighted sampling without replacement on the ordinary casting body texture token and the casting invalid background token to generate a candidate mask set and perform defect-sensitive core token verification. S53. Implement a hard constraint on the number of global mask tokens to ensure that the total number of mask tokens in each iteration is consistent with the number of target masks calculated from the dynamic base mask rate; S54. Implement spatial discrete constraints to limit the number of consecutive mask image blocks in the horizontal, vertical, or diagonal directions to no more than 2, and prohibit the formation of closed mask rings surrounding the defect-sensitive core token.
[0014] Preferably, the specific content of step S6 is as follows: The token sequence after dynamic masking is input into the ViT-MAE model. The ViT encoder only processes visible tokens, and the MAE decoder combines mask tokens and positional encoding to reconstruct the masked region, obtaining the reconstructed image or reconstructed patch features. The calculation includes the joint loss of MAE image reconstruction, the loss of attention preservation in defect-sensitive regions, and the loss of defect neighborhood edge reconstruction. The ViT-MAE model parameters are updated in reverse based on the joint loss, and the global spatial attention heatmap, image patch gray-level gradient features, proportion of defect-sensitive core tokens, proportion of invalid background tokens, and dynamic global base mask rate are updated after each training round. This enables the masking strategy to adaptively iterate with the progress of casting defect feature learning, and achieves bidirectional collaborative optimization between the masking strategy and casting defect feature learning.
[0015] Preferably, in step S6, after pre-training is completed, the network parameters of the pre-trained encoder in the ViT-MAE model are transferred to the downstream casting surface defect detection model. Feature extraction is performed on the surface image of the casting to be detected, and the extracted defect features are classified and located through the downstream detection network to obtain the defect category, defect location and corresponding confidence level. For defect segmentation or classification tasks, the pixel-level segmentation result of the defect area or the defect category determination result are output respectively.
[0016] A hierarchical dynamic adaptive self-supervised masking system for casting surface defect detection, based on the aforementioned hierarchical dynamic adaptive self-supervised masking method for casting surface defect detection, includes: a data acquisition and preprocessing module, a data evaluation module, a dynamic mask rate calculation module, a hierarchical mask control module, a semantic mask sampling module, and a training iteration module; The data acquisition and preprocessing module is used to acquire and preprocess the original images of the surface of castings from industrial production lines. The data evaluation module is used to divide the preprocessed casting image into image blocks, embed codes for each image block and fuse them with position codes to form an input token sequence; combining the global spatial attention heatmap and the gray-level gradient features of the image blocks, based on the defect sensitivity score of each image block token, all image block tokens are divided into three levels: defect sensitive core token, ordinary casting body texture token, and invalid casting background token. The dynamic mask rate calculation module is used to dynamically calculate the global basic mask rate by combining the proportion of defect-sensitive core tokens in the current casting image, the current training round of the model, and the proportion of invalid background tokens in the casting, and to determine the number of target mask tokens corresponding to the current training round based on the dynamic global basic mask rate. The layered mask control module is used to adjust the dynamic global base mask rate hierarchically based on the hierarchical visual perception mechanism of the visual Transformer encoder, using the dynamic global base mask rate as a benchmark, to obtain differentiated layered mask probabilities. The semantic mask sampling module is used to combine the image patch level and the differential level mask probability, and superimpose the forced mask-free constraint of defect region, the global mask number constraint and the spatial discrete mask constraint to perform weighted sampling of mask position and generate the final mask position set. The training iteration module is used to input the token sequence of the casting image after dynamic masking into the ViT-MAE model to perform forward reconstruction of the missing regions of the image, and to update the model parameters and dynamic mask parameters in reverse by combining the image reconstruction loss and the defect region attention retention loss. After multiple rounds of iterative training, a pre-trained ViT-MAE model is obtained and transferred to the downstream casting defect detection, segmentation or classification model.
[0017] A computer-readable storage medium having a computer program stored thereon, which, when executed by a processor, implements the aforementioned layered dynamic adaptive self-supervised masking method for detecting surface defects in castings.
[0018] A computer device includes a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor, when executing the program, implements a layered dynamic adaptive self-supervised masking method for detecting surface defects in castings.
[0019] As can be seen from the above technical solutions, compared with the prior art, this invention discloses a hierarchical dynamic adaptive self-supervised masking method and system for surface defect detection of castings. It identifies defect-sensitive areas by jointly using attention heatmaps and gray-level gradients as dual indicators, and can still protect high-risk areas such as sand holes, fine cracks, and pore edges even in scenarios with no or few fine annotations. It drives the base mask rate by jointly using defect proportion, training rounds, and texture sparsity, avoiding the simultaneous damage to the preservation of minor defects and background stripping by a single fixed mask rate. It conforms to the hierarchical modeling rules of visual Transformers from local details to global semantics by using differentiated mask probabilities for shallow, middle, and high-level groups. It reduces the risk of crack breakage, defect edge loss, and context misjudgment caused by continuous masks by using mask-free defect regions and spatial discrete constraints. The masking strategy operates on pre-trained mask scheduling and loss constraints without changing the backbone structure of the downstream detection network, making it easy to integrate into existing casting defect detection processes. Attached Figure Description
[0020] To more clearly illustrate the technical solutions in the embodiments of the present invention or the prior art, the drawings used in the description of the embodiments or the prior art will be briefly introduced below. Obviously, the drawings described below are only embodiments of the present invention. For those skilled in the art, other drawings can be obtained based on the provided drawings without creative effort.
[0021] Figure 1 This is a flowchart of a layered dynamic adaptive self-supervised mask method for detecting surface defects in castings provided in an embodiment of the present invention; Figure 2 This is a schematic diagram of the image block level division method provided in an embodiment of the present invention; Figure 3 This is a schematic diagram of differential hierarchical mask probability control provided in an embodiment of the present invention; Figure 4 This is a schematic diagram illustrating the bidirectional closed-loop optimization of the masking strategy and the ViT-MAE model pre-training provided in this embodiment of the invention. Detailed Implementation
[0022] The technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.
[0023] Example 1 This invention discloses a layered dynamic adaptive self-supervised masking method for detecting surface defects in castings, such as... Figure 1 This includes the following steps: S1. Obtain the original image of the surface of the casting on the industrial production line and preprocess it. Divide the preprocessed casting image into image blocks. Embed an encoding in each image block and fuse it with the position encoding to form an input token sequence. S2. Combining the global spatial attention heatmap and image block grayscale gradient features, based on the defect sensitivity score of each image block token, all image block tokens are divided into three levels: defect sensitive core token, ordinary casting body texture token, and casting invalid background token. S3. Combine the proportion of defect-sensitive core tokens in the current casting image, the current training round of the model, and the proportion of invalid background tokens in the casting to dynamically calculate the global base mask rate, and determine the number of target mask tokens corresponding to the current training round based on the dynamic global base mask rate; S4. Based on the dynamic global base mask rate, and based on the hierarchical visual perception mechanism of the visual Transformer encoder, the dynamic global base mask rate is hierarchically adjusted to obtain the differentiated hierarchical mask probabilities corresponding to the shallow group, the middle group and the high group. S5. Combining the image block level and the differential level mask probability, and superimposing the defect region forced mask-free constraint, the global mask quantity constraint and the spatial discrete mask constraint, perform mask position weighted sampling to generate the final mask position set that satisfies the defect protection constraint, the global mask quantity constraint and the spatial discrete constraint. S6. Input the token sequence of the casting image after dynamic masking into the ViT-MAE model to perform forward reconstruction of the missing image region, and combine the image reconstruction loss and the defect region attention retention loss to update the model parameters and dynamic mask parameters in reverse. After multiple rounds of iterative training until the preset termination condition is met, the pre-trained ViT-MAE model is obtained and transferred to the downstream casting defect detection, segmentation or classification model.
[0024] In this embodiment, the preprocessing in step S1 includes: performing grayscale or multi-channel normalization on the image; for images with oil stains, reflections, dark light, edge shadows, or conveyor belt backgrounds, brightness normalization, contrast limitation enhancement, and invalid edge cropping can be performed first to reduce the impact of non-defect imaging factors on subsequent mask judgment; after dividing the image into blocks, each image block is linearly projected to obtain a patch token, which is then fused with the position code to form an input token sequence. The patch size can be set according to the casting defect scale. For example, a smaller patch size is used for small sand holes and fine cracks to improve the distinguishability of defect edges at the token level.
[0025] To further implement the above technical solutions, such as Figure 2 The specific content of step S2 is as follows: The attention response of each image block token in the spatial dimension is calculated, and the grayscale gradient response of each image block is also calculated. The attention response and grayscale gradient response are normalized respectively, and the defect sensitivity score is calculated by weighted fusion. All image block tokens are sorted according to the defect sensitivity score. Based on the image block token ranking, defect sensitive core tokens, casting invalid background tokens and ordinary casting body texture tokens are divided to obtain a token level set containing the level identifier of each image block token.
[0026] In this embodiment, the defect sensitivity score is:
[0027] in, For the first Defect sensitivity score for each image patch, For attention response, It is a gray-scale gradient response. Weights for attention metrics; Based on adaptive adjustments during the training phase, attention weights are reduced and gradient weights are increased in the early stages of training, while attention weights are increased in the later stages of training as the model's attention gradually stabilizes. When the first round of training or the attention heatmap is not yet stable, the defect sensitivity score is initialized with grayscale gradient, local contrast, and edge density. Using the current shallow or mid-level attention matrix of the ViT encoder, the responses of each attention head in the spatial dimension are averaged or weighted and fused to obtain the attention response corresponding to each patch token. When the model is in the first round of pre-training and the attention has not yet converged, the heatmap of the previous round of exponential moving average or the heatmap initialized by gradient and local contrast can be used instead. Apply Sobel, Scharr, or other edge gradient operators to the casting image, and calculate the gradient mean, gradient variance, and edge density within each patch to obtain the grayscale gradient response. Sand holes, porosity, cracks, and missing material edges in castings typically manifest as localized abrupt changes in grayscale and gradient concentration; therefore, the grayscale gradient response... It can compensate for the instability of simple attention response in the early stages of training.
[0028] For image patch level classification, in practical applications, the top 15% of tokens are classified as defect-sensitive core tokens, the bottom 20% of tokens are classified as casting invalid background tokens, and the remaining tokens are classified as ordinary casting body texture tokens. For continuous cracks or large-area slag inclusions, a neighborhood expansion can be performed on the defect-sensitive core tokens to protect the context near the defect edges. To avoid misjudgment caused by noise in a single image, the defect sensitivity score can be updated by exponential moving average within a mini-batch or a training epoch. If a token maintains a high sensitivity score for multiple consecutive epochs, its defect sensitivity level is increased; if its high response occurs only once and there is no obvious gradient support in the neighborhood, it is reverted to an ordinary casting body texture token.
[0029] To further implement the above technical solution, in step S3, the dynamic global base mask rate is specifically as follows:
[0030] in, Preset an initial reference mask rate for the casting inspection scenario. The proportion of the current casting image defect-sensitive core token to all image block tokens. , These represent the minimum and maximum values of the proportion of defect-sensitive core tokens in each casting image in the dataset; For the current training round, This represents the total number of pre-training rounds for the model. α represents the proportion of invalid background tokens in the current casting image to all image block tokens; α, β, and γ are the weight coefficients corresponding to defect sensitivity, training round, and background redundancy, respectively. , ε represents the lower and upper bounds of the dynamic global base mask rate, and ε is a very small constant to prevent the denominator from being zero.
[0031] In this embodiment, It can be estimated from the number of defect-sensitive core tokens, the expansion area of the neighborhood of the sensitive core tokens, or the area of the pseudo-defect region with two indicators; It can be calculated from the proportion of low gradient, low attention, and low local contrast tokens, and is used to characterize the proportion of invalid background or weak texture redundant regions in the current image. When T is high, it indicates that there are many redundant regions that can be masked, and the base mask rate can be appropriately increased. When T is low and the defect-sensitive regions are densely distributed, the base mask rate is reduced to protect the defect details.
[0032] To further implement the above technical solutions, such as Figure 3 In step S4, the visual Transformer encoder consists of multiple Transformer blocks, which are divided into shallow, medium and high layers according to the network depth. The shallow layer group is responsible for capturing local detailed features, reducing the masking probability, and fully preserving the details of tiny sand holes and fine cracks; the middle layer group is responsible for fusing the defect context space association and using the standard baseline masking probability; the high layer group is responsible for global defect morphology discrimination and defect classification, increasing the masking probability, and strengthening the model's ability to distinguish defects from normal casting surfaces; the masking probability of the shallow layer group < the masking probability of the middle layer group < the masking probability of the high layer group. In this embodiment, the shallow group mask probability Middle layer group mask probability High-level group mask probability rate Δ should be controlled between 8% and 12%.
[0033] In practical applications, if the encoder contains K Transformer blocks, then the 1st to K / 3rd blocks are the shallow layer group, the K / 3+1st to 2K / 3rd blocks are the middle layer group, and the remaining blocks are the high layer group. The hierarchical masking modifier operates on the token visibility scheduling or inter-layer candidate mask distribution during the pre-training stage, without changing the parameter structure of the Transformer block itself. Therefore, it can be used as an external masking strategy in existing ViT-MAE, Swin Transformer, or other Transformer-based casting detection pre-training frameworks.
[0034] To further implement the above technical solution, the specific content of step S5 is as follows: S51. Execute mandatory mask-free constraint for defect areas, assign mask sampling weight of 0 to defect-sensitive core tokens so that defect-sensitive core tokens do not participate in candidate mask position sampling; assign mask sampling weight of 1 to ordinary casting body texture tokens, and assign mask sampling weight η greater than 1 to casting invalid background tokens so that mask positions are preferentially distributed in the casting invalid background area, and η can be adaptively set according to the proportion of casting invalid background tokens. S52. Based on the differential hierarchical mask probability and the level sampling weight corresponding to each image block token, perform weighted sampling without replacement on the ordinary casting body texture token and the casting invalid background token to generate a candidate mask set and perform defect-sensitive core token verification. When the candidate mask set contains a defect-sensitive core token due to dynamic updates of the token level or adjustments to the mask set, the corresponding token will be removed from the candidate mask set, and the same number of tokens will be added from the ordinary casting body texture tokens or the invalid casting background tokens. S53. Implement a hard constraint on the number of global mask tokens to ensure that the total number of mask tokens in each iteration is consistent with the number of target masks calculated from the dynamic base mask rate; In this embodiment, let the total number of current image tokens be N, then the actual number of masks is... When the proportion of defect-sensitive tokens is too high, resulting in a shortage of maskable tokens, Pbase should be reduced first or sparse sampling should be performed from ordinary texture tokens to avoid forcibly meeting the mask quantity by destroying defective areas. S54. Implement spatial discrete constraints to limit the number of consecutive mask image blocks in the horizontal, vertical or diagonal direction to no more than 2, and prohibit the formation of closed mask rings surrounding the defect-sensitive core token; For the neighborhood of a long crack, the continuous shielding length on both sides of the crack direction can be further limited to prevent the crack context from being cut off.
[0035] To further implement the above technical solutions, such as Figure 4 The specific content of step S6 is as follows: The token sequence after dynamic masking is input into the ViT-MAE model. The ViT encoder only processes visible tokens, and the MAE decoder combines mask tokens and positional encoding to reconstruct the masked region, obtaining the reconstructed image or reconstructed patch features. The calculation includes the joint loss of MAE image reconstruction, the loss of attention preservation in defect-sensitive regions, and the loss of defect neighborhood edge reconstruction. In this embodiment, joint loss Specifically:
[0036] in, The pixel reconstruction loss or feature reconstruction loss is the loss of the masked patch; The attention retention loss for defect-sensitive regions is used to constrain the defect-sensitive core tokens to maintain sufficient attention response before and after the mask, preventing the defect region from being misclassified as background during training. This is used as the defect neighborhood edge reconstruction loss to enhance the reconstruction of defect neighborhood edges and improve the learnability of sand hole boundaries, fine crack contours, and missing material edges. and These are the loss weighting coefficients; The ViT-MAE model parameters are updated in reverse based on the joint loss, and the global spatial attention heatmap is updated after each training epoch. Image patch grayscale gradient features The percentage of defect-sensitive core tokens (L), the percentage of invalid background tokens (T), and the dynamic global base mask rate. This enables the masking strategy to adaptively iterate as the learning progress of casting defect features progresses, achieving bidirectional collaborative optimization between the masking strategy and the learning of casting defect features.
[0037] To further implement the above technical solution, in step S6, after pre-training is completed, the network parameters of the pre-trained encoder in the ViT-MAE model are transferred to the downstream casting surface defect detection model. Feature extraction is performed on the surface image of the casting to be detected, and the extracted defect features are classified and located through the downstream detection network to obtain the defect category, defect location and corresponding confidence level. For defect segmentation or classification tasks, the pixel-level segmentation result of the defect area or the defect category determination result are output respectively.
[0038] Example 2 A hierarchical dynamic adaptive self-supervised masking system for casting surface defect detection is provided. Based on a hierarchical dynamic adaptive self-supervised masking method for casting surface defect detection, the system includes: a data acquisition and preprocessing module, a data evaluation module, a dynamic mask rate calculation module, a hierarchical masking control module, a semantic masking sampling module, and a training iteration module. The data acquisition and preprocessing module is used to acquire and preprocess the original images of the surface of castings from industrial production lines. The data evaluation module is used to divide the preprocessed casting image into image blocks, embed codes for each image block and fuse them with position codes to form an input token sequence; combining the global spatial attention heatmap and the gray-level gradient features of the image blocks, based on the defect sensitivity score of each image block token, all image block tokens are divided into three levels: defect sensitive core token, ordinary casting body texture token, and invalid casting background token. The dynamic mask rate calculation module is used to dynamically calculate the global basic mask rate by combining the proportion of defect-sensitive core tokens in the current casting image, the current training round of the model, and the proportion of invalid background tokens in the casting, and to determine the number of target mask tokens corresponding to the current training round based on the dynamic global basic mask rate. The layered mask control module is used to adjust the dynamic global base mask rate hierarchically based on the hierarchical visual perception mechanism of the visual Transformer encoder, using the dynamic global base mask rate as a benchmark, to obtain differentiated layered mask probabilities. The semantic mask sampling module is used to combine the image patch level and the differential level mask probability, and superimpose the forced mask-free constraint of defect region, the global mask number constraint and the spatial discrete mask constraint to perform weighted sampling of mask position and generate the final mask position set. The training iteration module is used to input the token sequence of the casting image after dynamic masking into the ViT-MAE model to perform forward reconstruction of the missing regions of the image, and to update the model parameters and dynamic mask parameters in reverse by combining the image reconstruction loss and the defect region attention retention loss. After multiple rounds of iterative training, a pre-trained ViT-MAE model is obtained and transferred to the downstream casting defect detection, segmentation or classification model.
[0039] Example 3 A computer-readable storage medium having a computer program stored thereon that, when executed by a processor, implements a hierarchical dynamic adaptive self-supervised masking method for detecting surface defects in castings.
[0040] Example 4 A computer device includes a memory, a processor, and a computer program stored in the memory and executable on the processor. When the processor executes the program, it implements a layered dynamic adaptive self-supervised masking method for detecting surface defects in castings.
[0041] The various embodiments in this specification are described in a progressive manner, with each embodiment focusing on its differences from other embodiments. Similar or identical parts between embodiments can be referred to interchangeably. For the apparatus disclosed in the embodiments, since they correspond to the methods disclosed in the embodiments, the description is relatively simple; relevant parts can be referred to the method section.
[0042] The above description of the disclosed embodiments enables those skilled in the art to make or use the invention. Various modifications to these embodiments will be readily apparent to those skilled in the art, and the general principles defined herein may be implemented in other embodiments without departing from the spirit or scope of the invention. Therefore, the invention is not to be limited to the embodiments shown herein, but is to be accorded the widest scope consistent with the principles and novel features disclosed herein.
Claims
1. A layered dynamic adaptive self-supervised masking method for detecting surface defects in castings, characterized in that, Includes the following steps: S1. Obtain the original image of the surface of the casting on the industrial production line and preprocess it. Divide the preprocessed casting image into image blocks. Embed an encoding in each image block and fuse it with the position encoding to form an input token sequence. S2. Combining the global spatial attention heatmap and image block grayscale gradient features, based on the defect sensitivity score of each image block token, all image block tokens are divided into three levels: defect sensitive core token, ordinary casting body texture token, and casting invalid background token. S3. Combine the proportion of defect-sensitive core tokens in the current casting image, the current training round of the model, and the proportion of invalid background tokens in the casting to dynamically calculate the global base mask rate, and determine the number of target mask tokens corresponding to the current training round based on the dynamic global base mask rate; S4. Based on the dynamic global base mask rate, and based on the hierarchical visual perception mechanism of the visual Transformer encoder, the dynamic global base mask rate is hierarchically adjusted to obtain differentiated hierarchical mask probabilities. S5. Combining the image block level and the differential level mask probability, and superimposing the forced mask-free constraint for defect areas, the global mask quantity constraint and the spatial discrete mask constraint, perform weighted sampling of mask positions to generate the final mask position set; S6. Input the token sequence of the casting image after dynamic masking into the ViT-MAE model to perform forward reconstruction of the missing image region, and combine the image reconstruction loss and the defect region attention retention loss to update the model parameters and dynamic mask parameters in reverse. After multiple rounds of iterative training, the pre-trained ViT-MAE model is obtained and transferred to the downstream casting defect detection, segmentation or classification model.
2. The layered dynamic adaptive self-supervised mask method for surface defect detection of castings as described in claim 1, characterized in that, The specific content of step S2 is as follows: Calculate the attention response of each image patch token in the spatial dimension, and simultaneously calculate the grayscale gradient response of each image patch; normalize the attention response and grayscale gradient response respectively, and calculate the defect sensitivity score by weighted fusion; All image block tokens are sorted according to the defect sensitivity score. Based on the image block token ranking, defect sensitive core tokens, casting invalid background tokens, and ordinary casting body texture tokens are divided to obtain a token level set containing the level identifiers of each image block token.
3. The layered dynamic adaptive self-supervised mask method for surface defect detection of castings as described in claim 1, characterized in that, In step S3, the dynamic global base mask rate is specifically as follows: in, Preset an initial reference mask rate for the casting inspection scenario. The proportion of the current casting image defect-sensitive core token to all image block tokens. , These represent the minimum and maximum values of the proportion of defect-sensitive core tokens in each casting image in the dataset; For the current training round, This represents the total number of pre-training rounds for the model. α represents the proportion of invalid background tokens in the current casting image to all image block tokens; α, β, and γ are the weight coefficients corresponding to defect sensitivity, training round, and background redundancy, respectively. , ε represents the lower and upper bounds of the dynamic global base mask rate, and ε is a very small constant to prevent the denominator from being zero.
4. The layered dynamic adaptive self-supervised mask method for surface defect detection of castings as described in claim 1, characterized in that, In step S4, the visual Transformer encoder consists of multiple Transformer blocks, which are divided into shallow, medium and high layer groups according to network depth. The shallow layer group is responsible for capturing local detailed features, reducing the masking probability, and fully preserving the details of tiny sand holes and fine cracks; the middle layer group is responsible for fusing the defect context space association and using the standard baseline masking probability; the high layer group is responsible for global defect morphology discrimination and defect classification, increasing the masking probability, and strengthening the model's ability to distinguish defects from normal casting surfaces; the masking probability of the shallow layer group < the masking probability of the middle layer group < the masking probability of the high layer group.
5. The layered dynamic adaptive self-supervised mask method for surface defect detection of castings as described in claim 1, characterized in that, The specific content of step S5 is as follows: S51. Execute mandatory mask-free constraint on defect regions, assign a mask sampling weight of 0 to defect-sensitive core tokens, assign a mask sampling weight of 1 to ordinary casting body texture tokens, and assign a mask sampling weight η greater than 1 to invalid casting background tokens. S52. Based on the differential hierarchical mask probability and the level sampling weight corresponding to each image block token, perform weighted sampling without replacement on the ordinary casting body texture token and the casting invalid background token to generate a candidate mask set and perform defect-sensitive core token verification. S53. Implement a hard constraint on the number of global mask tokens to ensure that the total number of mask tokens in each iteration is consistent with the number of target masks calculated from the dynamic base mask rate; S54. Implement spatial discrete constraints to limit the number of consecutive mask image blocks in the horizontal, vertical, or diagonal directions to no more than 2, and prohibit the formation of closed mask rings surrounding the defect-sensitive core token.
6. The layered dynamic adaptive self-supervised mask method for surface defect detection of castings as described in claim 1, characterized in that, The specific content of step S6 is as follows: The token sequence after dynamic masking is input into the ViT-MAE model. The ViT encoder only processes visible tokens, and the MAE decoder combines mask tokens and positional encoding to reconstruct the masked region, obtaining the reconstructed image or reconstructed patch features. The calculation includes the joint loss of MAE image reconstruction, the loss of attention preservation in defect-sensitive regions, and the loss of defect neighborhood edge reconstruction. The ViT-MAE model parameters are updated in reverse based on the joint loss, and the global spatial attention heatmap, image patch gray-level gradient features, proportion of defect-sensitive core tokens, proportion of invalid background tokens, and dynamic global base mask rate are updated after each training round. This enables the masking strategy to adaptively iterate with the progress of casting defect feature learning, and achieves bidirectional collaborative optimization between the masking strategy and casting defect feature learning.
7. The layered dynamic adaptive self-supervised mask method for surface defect detection of castings as described in claim 1, characterized in that, In step S6, after pre-training is completed, the network parameters of the pre-trained encoder in the ViT-MAE model are transferred to the downstream casting surface defect detection model. Feature extraction is performed on the surface image of the casting to be detected, and the extracted defect features are classified and located through the downstream detection network to obtain the defect category, defect location and corresponding confidence. For defect segmentation or classification tasks, the pixel-level segmentation result of the defect area or the defect category determination result are output respectively.
8. A layered dynamic adaptive self-supervised masking system for detecting surface defects in castings, characterized in that, A hierarchical dynamic adaptive self-supervised masking method for detecting surface defects in castings, based on any one of claims 1-7, includes: a data acquisition and preprocessing module, a data evaluation module, a dynamic mask rate calculation module, a hierarchical masking control module, a semantic masking sampling module, and a training iteration module; The data acquisition and preprocessing module is used to acquire and preprocess the original images of the surface of castings from industrial production lines. The data evaluation module is used to divide the preprocessed casting image into image blocks, embed codes for each image block and fuse them with position codes to form an input token sequence; combining the global spatial attention heatmap and the gray-level gradient features of the image blocks, based on the defect sensitivity score of each image block token, all image block tokens are divided into three levels: defect sensitive core token, ordinary casting body texture token, and invalid casting background token. The dynamic mask rate calculation module is used to dynamically calculate the global basic mask rate by combining the proportion of defect-sensitive core tokens in the current casting image, the current training round of the model, and the proportion of invalid background tokens in the casting, and to determine the number of target mask tokens corresponding to the current training round based on the dynamic global basic mask rate. The layered mask control module is used to adjust the dynamic global base mask rate hierarchically based on the hierarchical visual perception mechanism of the visual Transformer encoder, using the dynamic global base mask rate as a benchmark, to obtain differentiated layered mask probabilities. The semantic mask sampling module is used to combine the image patch level and the differential level mask probability, and superimpose the forced mask-free constraint of defect region, the global mask number constraint and the spatial discrete mask constraint to perform weighted sampling of mask position and generate the final mask position set. The training iteration module is used to input the token sequence of the casting image after dynamic masking into the ViT-MAE model to perform forward reconstruction of the missing regions of the image, and to update the model parameters and dynamic mask parameters in reverse by combining the image reconstruction loss and the defect region attention retention loss. After multiple rounds of iterative training, a pre-trained ViT-MAE model is obtained and transferred to the downstream casting defect detection, segmentation or classification model.
9. A computer-readable storage medium having a computer program stored thereon, characterized in that, When the program is executed by the processor, it implements a hierarchical dynamic adaptive self-supervised mask method for detecting surface defects in castings as described in any one of claims 1 to 7.
10. A computer device, comprising a memory, a processor, and a computer program stored in the memory and executable on the processor, characterized in that, When the processor executes the program, it implements a layered dynamic adaptive self-supervised mask method for detecting surface defects in castings as described in any one of claims 1 to 7.
