Thangka image restoration method and system and storage medium
Through the encoder-decoder structure based on the Transformer model and the parallel CSWin resolution Transformer module, combined with the vector quantization codebook and the multi-scale feature guidance module, the problem of repair errors in Thangka images with complex structures and rich textures is solved. In order to achieve high-quality image repair and structural integrity, the comprehensive quality evaluation index is used to optimize the learning rate and improve the repair effect.
Patent Information
- Application Number
- CN202410843431.8
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2024-06-27
- Publication Date
- 2024-09-27
- Estimated Expiration
- 2044-06-27
AI Technical Summary
When the existing technology processes Thangka images with rich textures and complex structures, the accuracy of predicting a priori information is low, leading to repair errors, and it fails to effectively utilize the structural information of the image and cannot maintain the structural integrity of the image, especially When a large area is damaged, and the quality evaluation index is single, there is a lack of multi-dimensional comprehensive evaluation.
The encoder-decoder structure based on the Transformer model is used, combined with the vector quantization codebook and the parallel CSWin resolution Transformer module, to isolate local information and capture structural information of the image through nonlinear transformation and multi-scale feature guidance modules, and through comprehensive The quality evaluation index dynamically adjusts the learning rate to optimize the repair effect.
It achieves high-quality restoration of thangka images, improves the fidelity and structural consistency of the restoration results, optimizes the learning rate through multi-dimensional quality evaluation indicators, and improves the restoration effect and fidelity.
Smart Images

Figure CN118710552A
Abstract
Description
Technical Field
[0001] The present invention relates to the technical field of digital image processing, and in particular to a thangka image restoration method, system and storage medium. Background Art
[0002] In the field of digital image processing, image restoration technology has always been a hot topic of research. Its purpose is to repair damaged image content through computational methods in order to restore the integrity and beauty of the image. This field began in the late 20th century and mainly relied on simple interpolation algorithms, such as nearest neighbor interpolation and bilinear interpolation in the early days. In the 21st century, with the rapid development of computer vision and machine learning, image restoration technology has been significantly improved. In particular, the rise of deep learning has made neural network-based image restoration methods, such as convolutional neural networks (CNN) and generative adversarial networks (GAN), gradually become mainstream. They can learn complex mappings of large amounts of data and achieve highly complex image restoration effects. However, traditional methods and early deep learning methods are not good at processing images with rich textures and complex structures. However, unlike natural images, the patterns of the costumes, instruments, flowers, vines, clouds, and mountains and rivers in the thangka are complex and exquisite, with rich details. When facing such thangka images, the accuracy of the prior information predicted by such methods will be greatly reduced, resulting in a large range of restoration errors when filling in internal textures. When dealing with artworks such as thangkas, there are still huge challenges.
[0003] The shortcomings of existing technologies are mainly reflected in the limitations of repairing highly structured and finely detailed image content. In particular, thangka images usually contain fine lines and complex patterns. Once these contents are damaged, it is difficult to achieve satisfactory repair effects using simple texture replication or basic learning models. In addition, existing technologies often ignore the global consistency of the image and the restoration of local details during the repair process, resulting in the inability of the repaired image to be seamlessly connected with the original image visually. More importantly, most methods fail to effectively utilize the intrinsic structural information of the image and cannot maintain the structural integrity of the image during the repair process, especially when there is large-scale damage. This problem is particularly prominent. While the generative adversarial network (GAN) performs well in providing realistic textures for repaired images, its training stability and mode collapse are still problems that need to be solved. In addition, the quality evaluation indicators in existing technologies are mostly single indicator evaluations, lacking a multi-dimensional comprehensive evaluation of image quality.
[0004] The above information disclosed in this Background section is only for enhancement of understanding of the background of the present disclosure and therefore it may contain information that does not constitute the prior art that is already known to one of ordinary skill in the art. Summary of the invention
[0005] The purpose of the present invention is to provide a thangka image restoration method, system and storage medium to solve the problems raised in the above background technology.
[0006] To achieve the above object, the present invention provides the following technical solutions:
[0007] A thangka image restoration method, the specific steps comprising:
[0008] Step S1, collecting thangka images containing damaged parts and missing parts, and preprocessing the collected thangka images, and constructing the preprocessed thangka images into an image data set;
[0009] Step S2, constructing an encoder-decoder structure based on the Transformer model and using it to jointly learn a discrete codebook, inputting the thangka image in the image data set into the constructed encoder, using the encoder to divide the input thangka image into non-overlapping sub-regions of fixed size, and mapping the sub-regions to a continuous latent space representation through a nonlinear transformation to obtain a feature vector;
[0010] Step S3, introducing a vector quantization codebook, and performing vector quantization on the continuous potential feature vector output by the encoder, wherein the discrete codebook is constructed by using a clustering algorithm, and each vector in the codebook represents a potential space representation of a sub-region in the image, and finally the obtained discrete codebook is used as codebook prior knowledge;
[0011] Step S4, construct a parallel CSWin resolution Transformer module, which adopts the design of cross-shaped window and local enhanced position encoding, takes the feature vector in step S3 as input, adds additional learnable position embedding to the feature vector to preserve spatial information, and then flattens the feature vector along the spatial dimension to obtain the final input of the module to predict the probability distribution of the next index;
[0012] Step S5: Use the parallel CSWin resolution Transformer module in step S4 to accurately infer the index of the missing token, and use these indexes to find the corresponding discrete vectors from the discrete codebook obtained in step S3 for image restoration. After completing one restoration attempt, the system will enter an iterative loop;
[0013] Step S6, after each iteration, collect the generated repaired image, and obtain the structural similarity index and peak signal-to-noise ratio PSNR of the repaired image, and analyze and process the similarity index and peak signal-to-noise ratio PSNR to generate a comprehensive quality evaluation index QI, which is used to evaluate the image quality and the repair effect, and generate a corresponding learning rate secondary adjustment strategy;
[0014] Step S7, based on the adaptive learning rate adjustment, a multi-scale feature guidance module is designed, which utilizes the features of the non-damaged area to promote the consistency of the generated area with the non-damaged area in structure and texture, thereby improving the quality and fidelity of the repair result;
[0015] Step S8: During the repair process, dynamically adjust the learning rate of the model according to the comprehensive quality evaluation index QI and the learning rate adjustment strategy generated in step S6 to optimize the repair effect;
[0016] Step S9: After all iterations are completed, the final restored thangka image is post-processed, including but not limited to image enhancement, color correction and detail optimization, to improve the quality and visual effect of the restored image, and finally the restored thangka image is output.
[0017] Furthermore, after each iteration, the generated repaired image is collected, and the structural similarity index and peak signal-to-noise ratio (PSNR) of the repaired image are obtained. The similarity index and peak signal-to-noise ratio (PSNR) are analyzed and processed to generate a comprehensive quality evaluation index (QI), which is used to evaluate the image quality and the repair effect, and to generate a corresponding secondary adjustment strategy for the learning rate.
[0018] After each iteration, the resulting inpainted image is collected and the following quality parameters are calculated:
[0019] The structural similarity index SSIM is as follows:
[0020]
[0021] Where x and y are the local windows of the reference image and the repaired image, respectively, and μ x , μ y is the mean, is the variance, σ xy is the covariance, c1 and c2 are constants used to stabilize the calculation;
[0022] The peak signal-to-noise ratio PSNR is as follows:
[0023]
[0024] Among them, MAX I is the maximum value of the image pixels, MSE(x,y) is the mean square error;
[0025] Combining SSIM and PSNR, a comprehensive quality evaluation index QI is generated. The calculation formula is as follows:
[0026]
[0027] Parameter explanation, ω iis a weight factor used to balance the impact of different quality assessment indicators, where ω1, ω2, ω3, and ω4 correspond to the weights of SSIM, PSNR, FSIM, and NIQE, respectively;
[0028] f(Metric i″′ ) is a complex function, i″′∈{1, 2, 3, 4}, where Metric i″′ When i″′ takes the values of 1, 2, 3, and 4, it represents SSIM, PSNR, FSIM, and NIQE, respectively, and is used to perform nonlinear transformation on each quality assessment indicator. The formula is as follows:
[0029] f(SSIM)=log(1+SSIM)
[0030] f(PSNR) = exp(-PSNR / 100)
[0031]
[0032] g(NIQE) is a normalization function used to adjust the impact of NIQE. x∈NIQE;
[0033] The value range of QI is set to (0,1). When QI is close to 1, it means that the image quality is close to the original image and the restoration effect is good; when QI is close to 0, it means that the image quality is poor and the restoration effect is not good.
[0034] Furthermore, when the QI value increases, it means that the image restoration quality is improved and the image is closer to the visual and structural features of the original image; conversely, a decrease in the QI value indicates that the restoration effect is poor and the model parameters or training strategy need to be adjusted;
[0035] According to the changes in these indicators, the learning rates of the generator and discriminator are dynamically adjusted. If the quality evaluation indicators improve slowly or decrease, the learning rate is increased to explore new parameter spaces; if the quality evaluation indicators improve steadily, the learning rate is maintained or moderately reduced to stabilize the training; specifically, the following are included:
[0036] According to the generated quality evaluation index QI, the learning rate is adjusted twice:
[0037] 1 t+1 =lr t ·(1+β5·(QIt-QItarget))
[0038] Among them, QIt is the quality evaluation index at the tth iteration, QItarget is the target quality evaluation index, and β5 is the adjustment factor used to control the impact of the quality evaluation index on the learning rate;
[0039] In interval 1 (0, 0.3), the image quality is poor, and the learning rate needs to be increased to explore new parameters and quickly improve the image restoration effect. The threshold is set to 0.2. When it is lower than this value, the learning rate is urgently increased in order to achieve significant improvement.
[0040] Interval 2: [0.3, 0.7), there is room for improvement in image quality; an adjustment strategy is adopted to maintain or slightly increase the learning rate to steadily improve image quality, with a threshold of 0.5 to maintain training stability and continuous improvement;
[0041] Interval three [0.7, 1) indicates that the image quality is close to ideal. In this interval, the learning rate is reduced to stabilize the training and prevent overfitting. The threshold is set to 0.85. When it exceeds this value, the learning rate is further reduced to ensure continuous optimization and stability of quality.
[0042] A thangka image restoration system, the system is used to execute the method described.
[0043] A storage medium stores a computer program, which implements the steps of the thangka image restoration method when executed by a processor.
[0044] Compared with the prior art, the present invention has the following beneficial effects:
[0045] 1. A novel codebook learning framework is designed, in which the encoder divides the input image into non-overlapping sub-regions (patches) of fixed size and then nonlinearly transforms them into latent feature vectors, ensuring effective isolation of local information. The vector quantization codebook is introduced to more effectively capture and preserve the structural information and details of the image, thereby producing more realistic results in the reconstruction process.
[0046] 2. Design a parallel CSWinTransformer module, a cross-shaped window and a local enhanced position encoding design, which enhances the context modeling capability while reducing the computational cost and improving the accuracy of index prediction;
[0047] 3. An innovative multi-scale feature guidance module is designed, in which LKAs of different scales use local information and channel adaptability to better learn feature information of non-defective areas;
[0048] 4. The CDCT model has been extensively experimented with existing cutting-edge methods on Celeba-HQ, Places2, and self-made thangka datasets. Qualitative and quantitative experiments show that the restoration results of the CDCT model are competitive, opening up a novel technical path for the restoration of cultural heritage such as thangka images.
[0049] 5. SSIM and PSNR are used as quality evaluation indicators, and the comprehensive quality evaluation index QI is introduced. Through the multi-dimensional evaluation of the image restoration results, the secondary adjustment of the learning rate is realized, which further improves the restoration quality;
[0050] In summary, in the codebook learning stage, a network framework based on vector quantization codebook is designed and improved to discretize the intermediate features of the encoded input image and obtain a context-rich discrete codebook; in the second stage, a parallel Transformer module based on a cross window is proposed, which can accurately predict the index combination of the missing area of the image with limited computational cost; in addition, a multi-scale feature guidance module is proposed to gradually fuse the features of the undamaged area with the texture features in the codebook, so as to better preserve the local details of the undamaged area. BRIEF DESCRIPTION OF THE DRAWINGS
[0051] Figure 1 It is a schematic diagram of the overall method flow of the present invention;
[0052] Figure 2 It is a schematic diagram of the overall framework of the CDCT model of the present invention;
[0053] Figure 3 It is a schematic diagram of the parallel CSWin resolution Transformer module of the present invention;
[0054] Figure 4 It is a schematic diagram of a multi-scale feature guiding module of the present invention;
[0055] Figure 5 It is a schematic diagram of a curve showing a change in loss value versus the number of iterations of the present invention;
[0056] Figure 6 This is the qualitative comparison result of the present invention on the Celeba-HQ dataset;
[0057] Figure 7 This is the qualitative comparison result of the present invention on the places2 dataset;
[0058] Figure 8 This is the qualitative comparison result of the present invention on the self-made thangka dataset;
[0059] Fig. 9 It is a schematic diagram for analyzing the visual effects of various components of the model of the present invention. DETAILED DESCRIPTION
[0060] In order to make the objectives, technical solutions and advantages of the present invention more clearly understood, the present invention is further described in detail below in conjunction with specific embodiments.
[0061] It should be noted that, unless otherwise defined, the technical terms or scientific terms used in the present invention should be understood by people with ordinary skills in the field to which the present invention belongs. The words "first", "second" and similar words used in the present invention do not indicate any order, quantity or importance, but are only used to distinguish different components. "Include" or "comprise" and similar words mean that the elements or objects appearing before the word include the elements or objects listed after the word and their equivalents, without excluding other elements or objects. "Connect" or "connected" and similar words are not limited to physical or mechanical connections, but may include electrical connections, whether direct or indirect. "Up", "down", "left", "right" and the like are only used to indicate relative positional relationships. When the absolute position of the described object changes, the relative positional relationship may also change accordingly.
[0062] Embodiment 1:
[0063] See also Figures 1 to 9 , the present invention provides a technical solution:
[0064] A thangka image restoration method, the specific steps comprising:
[0065] Step S1, collecting thangka images containing damaged parts and missing parts, and preprocessing the collected thangka images, and constructing the preprocessed thangka images into an image data set;
[0066] Step S2, constructing an encoder-decoder structure based on the Transformer model and using it to jointly learn a discrete codebook, inputting the thangka image in the image data set into the constructed encoder, using the encoder to divide the input thangka image into non-overlapping sub-regions of fixed size, and mapping the sub-regions to a continuous latent space representation through a nonlinear transformation to obtain a feature vector;
[0067] Step S3, introducing a vector quantization codebook, and performing vector quantization on the continuous potential feature vector output by the encoder, wherein the discrete codebook is constructed by using a clustering algorithm, and each vector in the codebook represents a potential space representation of a sub-region in the image, and finally the obtained discrete codebook is used as codebook prior knowledge;
[0068] Step S4, construct a parallel CSWin resolution Transformer module, which adopts a cross-shaped window and a local enhanced position encoding (LePE) design, takes the feature vector in step S3 as input, adds an additional learnable position embedding to the feature vector to preserve spatial information, and then flattens the feature vector along the spatial dimension to obtain the final input of the module to predict the probability distribution of the next possible index;
[0069] Step S5: Use the parallel CSWin resolution Transformer module in step S4 to accurately infer the index of the missing token, and use these indexes to find the corresponding discrete vectors from the discrete codebook obtained in step S3 for image restoration. After completing one restoration attempt, the system will enter an iterative loop;
[0070] Step S6, after each iteration, collect the generated repaired image, and obtain the structural similarity index and peak signal-to-noise ratio PSNR of the repaired image, and analyze and process the similarity index and peak signal-to-noise ratio PSNR to generate a comprehensive quality evaluation index QI, which is used to evaluate the image quality and the repair effect, and generate a corresponding learning rate secondary adjustment strategy;
[0071] Step S7, based on the adaptive learning rate adjustment, a multi-scale feature guidance module is designed, which utilizes the features of the non-damaged area to promote the consistency of the generated area with the non-damaged area in structure and texture, thereby improving the quality and fidelity of the repair result;
[0072] Step S8: During the repair process, dynamically adjust the learning rate of the model according to the comprehensive quality evaluation index QI and the learning rate adjustment strategy generated in step S6 to optimize the repair effect;
[0073] Step S9: After all iterations are completed, the final restored thangka image is post-processed, including but not limited to image enhancement, color correction and detail optimization, to improve the quality and visual effect of the restored image, and finally the restored thangka image is output.
[0074] Embodiment 2:
[0075] Based on the first embodiment, in the shared codebook learning phase, the system architecture includes three core components: a codebook encoder E, a codebook decoder G, and a codebook containing K discrete codes. This is a set of K discrete codes, each c k is a code word that represents a specific feature or pattern;
[0076] When processing the input image When the codebook encoder E first converts the image I t Transformed into a latent representation Z in a high-dimensional space, Represents an image with height H, width W and 3 color channels;
[0077] Right now Here d represents the number of dimensions that make up this latent vector; m×n is the spatial resolution in the latent representation;
[0078] Then, an element-wise quantization operation q(·) is used, which is a function used to quantize each vector in the potential representation Z to the closest codeword in the codebook C. This operation is performed element by element, that is, each element (i, j) in Z is quantized separately;
[0079] Quantize each vector in this spatial latent representation Z to the nearest codeword c in the codebook k , thus obtaining the vector quantized output Z c and the corresponding code token sequence s∈{0,…,N-1} m′·n′ :
[0080]
[0081] Among them, each element It's Z (i,j) The closest codeword found in codebook C; the quantization operation is performed by calculating the distance ||Z (i,j) -c k ||And select the code word corresponding to the minimum distance to achieve;
[0082] Then, the decoder G is given Z c Reconstruct high-quality image I rec The m′·n′ code token sequence s formed represents a new potential discrete representation, which clearly indicates the codeword index at each position in the learned codebook. (i,j) = k, Overall Reconstruction I rec ≈I t Formulated as:
[0083] I rec =G(Z c )=G(q(E(I))) (4)
[0084] The encoder performs a mapping operation to convert the image data of size H×W into a discrete encoding form of scale H / m×W / n, where the parameters m and n indicate the downsampling ratio;
[0085] This process is essentially to transform the image I t The information of each m×n region in the Z is condensed into a single coding unit. c When any coding element in the original image I is t Corresponding coverage in space; The codebook and model are trained end-to-end through reconstruction loss. This application adopts four image-level reconstruction losses, including L1 loss L1, perceptual loss L per , against the loss L adv and style loss L style ;
[0086] The specific loss function is defined as follows:
[0087]
[0088] Here, Φ refers to the feature extractor in the VGG19 network. Due to the insufficient loss constraints at the image level when updating the codebook terms,
[0089] I t Represents the target image, that is, the image generated by the model is expected to be close to the reference image;
[0090] I rec represents the reconstructed image, ‖I t -I rec ‖1 represents the L1 distance between the target image and the reconstructed image, which is the sum of the absolute values of the differences between each corresponding pixel value of the two images;
[0091] Φ refers to the feature extractor in the VGG19 network;
[0092] Φ(I t ) and Φ(I rec ) represent the feature representations of the target image and the reconstructed image extracted using the pre-trained deep neural network, respectively;
[0093] represents the square of the Euclidean distance between the two sets of feature representations, which is used to measure the perceptual difference between the two images;
[0094] D(I t ) and D(I rec ) represent the discriminant results of the target image and the reconstructed image, respectively, where D is the discriminator network;
[0095] log D(I t ) and log(1-D(I rec )) represent the logarithm of the probability that the discriminator correctly identifies the target image and incorrectly identifies the reconstructed image;
[0096] and Represent the Gram matrices of the target image and the reconstructed image on the kth feature channel respectively, where Represents the parameters of the kth feature channel;
[0097] represents the expected value of the L1 distance between the Gram matrices on all feature channels, which is used to measure the difference in style between two images. k is the number of elements in the kth feature channel;
[0098] Therefore, this application also adopts the loss L at the intermediate code level quantize To reduce the difference between the codebook C and the embedded input feature Z;
[0099]
[0100] Here, sg(·) refers to the stopping gradient operator, and the parameter β is set to 0.25 to balance the weight between the encoder and codebook update speed;
[0101] In view of the fact that the feature quantization process shown in formula (1) is not differentiable, a direct transfer strategy is adopted, that is, the gradient is mirrored from the decoding stage to the encoding stage during back propagation to ensure the implementation of back propagation;
[0102] In order to comprehensively guide the prior knowledge learning of the codebook, the comprehensive loss function L codebook As an optimization target, it drives the entire end-to-end training process;
[0103] L codebook =L1+L per +L quantize +λ adv ·L adv +L style (7)
[0104] Among them, in the experiment of the application, λ adv Set to 0.8;
[0105] Although more codebook entries can simplify reconstruction, redundant elements will cause ambiguity in subsequent code prediction. Therefore, the CDCT method of the present application sets the number of codebook entries N to 1024, which is sufficient to achieve accurate image reconstruction; in addition, the codebook dimension d is set to 256.
[0106] Embodiment three:
[0107] Further explained on the basis of the second embodiment, the design points of the codebook encoder E specifically include:
[0108] Traditional CNN-based encoders process the input image using several convolution kernels in a sliding window manner, which is not suitable for image restoration because they introduce interference between masked and unmasked areas. Therefore, the encoder in the shared codebook learning stage is designed to process the input image in a non-overlapping patch manner and through multiple linear residual layers;
[0109] Specifically, the token representation is extracted in 8 blocks using a linear residual structure. In each block, two sets of GELU activation functions, linear layers, and residual connections are included;
[0110] First, the input image is unfolded to a size of (3×m×n,L), where L is the number of blocks. Then, the feature is transformed to a size of (L,d) through an adjustment layer.
[0111] Then, in each block, the input features are transformed from 256 to 128 dimensions and from 128 to 256 dimensions. After the feature extraction of eight linear residual layers, the potential representation Z is obtained through the fold operation.
[0112] A large compression ratio of r = H / n = W / m = 32 is obtained, which makes the global modeling in the second stage robust against degradation and tractable in computational cost;
[0113] The decoder G of the present application consists of 3 transposed convolutions and 1 convolution layer for upsampling; the size of the deconvolution kernel is 4×4, which means that the width and height of the deconvolution kernel are both 4; the stride is 2, which means that the sliding step length of the deconvolution kernel on the input image is 2;
[0114] The padding size is 1, which means padding one pixel at the edge of the input image to maintain the spatial size of the output. First, the feature with a dimension of 256×32×32 is upsampled to 64×256×256 through three transposed convolutions, and then the output is adjusted to 256×256×3 through a convolution with a convolution kernel size of 3×3, a reflection padding parameter of 1, and a stride of 1 to obtain the reconstructed image.
[0115] Embodiment 4:
[0116] Further explanation based on the third embodiment, the image restoration stage based on codebook prior specifically includes the following contents:
[0117] In the existing Transformer architecture for image restoration and completion, the index of quantized pixels is used as both input and prediction target. Although this strategy of using context index to predict missing index improves computational efficiency, this type of Transformer input will cause serious information loss problem, which is not conducive to index sequence prediction. Therefore, the parallel CSWinTransformer module (PCT) designed in this application directly converts the feature vector of the codebook encoder into As input, it helps to make more accurate predictions while reducing information loss;
[0118] Parallel CSWinTransformer modules such as Figure 3 As shown,
[0119] For the feature vector An additional learnable position embedding is added to preserve spatial information, and the feature vector is subsequently flattened along the spatial dimension to obtain the final input to this module;
[0120] The model uses 12 parallel CSWinTransformer blocks, where each block consists of a parallel multi-head self-attention block and a cross-window attention block, and a feedforward layer (Feedforward1);
[0121] The number of self-attention heads is set to 8. Different from the common Transformer module, the PCT module combines multiple heads and cross-shaped windows, which greatly reduces the amount of calculation and achieves better restoration effect. In addition, the cross-shaped window attention block adds a position encoding mechanism LePE on the linear projection value V to enhance the local inductive bias;
[0122] It is worth noting that the cross-window attention and full self-attention in the PCT module are trained from different receptive fields and connected together through residuals. Therefore, the standard self-attention block is not affected by the CSWin attention block. The Swish function in the feedforward layer 1 can better smooth the gradient while preserving the nonlinear characteristics of ReLU.
[0123] The design of the cross-shaped window and the local enhanced position encoding is as follows:
[0124] Different from axial attention, the cross-shaped window attention splits the channel into horizontal and vertical stripes, with half of the head capturing horizontal stripe attention and the other half capturing vertical stripe attention;
[0125] Taking horizontal stripe self-attention as an example, the feature matrix S is divided into a series of horizontal stripe segments with width b and no overlap [S 1 ,..,S N ], where N = H / b, and each stripe segment contains elements of b columns and W rows; in addition, the hyperparameter b is flexibly adjusted to strike a balance between learning ability and computational cost. Assuming that the dimensions of the query, key, and value vectors corresponding to each head are d, the horizontal stripe self-attention output processed by each head is defined as follows:
[0126] S=[S 1 ,S 2 ,…,S N ],
[0127] Y i =Attention(S i W Q ,S i W K ,S i W V ),(8)
[0128] Attention H(S) = [Y 1 ,Y 2 ,…,Y N ]
[0129] Where S i ∈R (b×W)×C , i=1,...,N,W Q ∈R C×d , W K ∈R C×d , W V ∈R C×d They represent the query matrix, key matrix, and value matrix obtained after each head performs linear transformation on the input feature matrix;
[0130] S=[S 1 ,S 2 ,…,S N ] indicates that the feature matrix S is divided into a series of horizontal stripe segments with a width of b and no overlap. i Contains elements in columns b and rows W;
[0131] N = H / b means that N is the number of horizontal stripe segments, which is equal to the height H of the feature matrix divided by the width b of each stripe segment;
[0132] S i ∈R (b×W)×C Represents each stripe segment S i is a b×W matrix, where b is the number of columns, W is the number of rows, and C is the feature dimension;
[0133] W Q ∈R C×d , W K ∈R C×d , W V ∈R C×d These are weight matrices of the linear transformation used to transform the input feature matrix S i Converted into query matrix (Query), key matrix (Key) and value matrix (Value), C is the dimension of input features, d is the dimension of each head (head);
[0134] Y i =Attention(S i W Q ,S i W K ,S i W V ) indicates that this is the calculation process of the attention mechanism, where S i W Q ,S i W KThey are the linear transformation results of query, key and value, and the output Y calculated by the attention mechanism i is the attention output of the i-th horizontal stripe segment;
[0135] Attention H (S) = [Y 1 ,Y 2 ,…,Y N ] indicates that this is the set of attention output results of all horizontal stripe segments, expressed as the attention output in the horizontal direction;
[0136] Attention V (S) indicates that this is the output result of the local self-attention operation performed on the vertical stripe area, expressed as the attention output in the vertical direction;
[0137] Similarly, the local self-attention operation performed on the vertical stripe area can also be derived accordingly, and the output result corresponding to each head is obtained using Attention V (S) to indicate;
[0138] The output of the PCT module passes through a linear layer and is mapped into a probability distribution using the Softmax function, which corresponds to the probability distribution of the K potential vectors in the codebook e; that is, the probability that the image block corresponds to the feature in the codebook;
[0139] In order to quantify the degree of agreement between the model prediction and the class label, the PCT module is trained to predict the probability distribution p(s i |s <i ), making the training objective equal to minimizing the negative log-likelihood of the data representation:
[0140] L Transformer =E x′~p(x′) [-logp(s)] (9)
[0141] Where p(s) = ∏ i p(s i |s <i );
[0142] p(s i |s <i ) is a conditional probability distribution, representing all elements s with index less than i in the known sequence <i Under the condition of i The probability distribution of , which is learned by the PCT module during training;
[0143] L TransformerIt is the loss function of the Transformer model, which is used to quantify the consistency between the model prediction and the true category label. During the training process, the goal is to minimize this loss function;
[0144] E x~p(x′) It is the symbol of expected value, which means averaging the samples x′ drawn from the data distribution p(x′). Here, it means calculating the average of the loss function for all possible data samples x′.
[0145] -logp(s) is the negative log-likelihood, which is used to calculate the difference between the probability distribution p(s) predicted by the model and the true label s. The negative log-likelihood is a commonly used loss function for optimizing probability models.
[0146] p(s)=∏ i p(s i |s <i ) is the product of the probability distributions of all indices in the sequence, which represents the model's predicted probability for the entire sequence, where each index s i The probability is based on all previous indexes s i The conditional probability of
[0147] In each iteration, the quality of the generated image is evaluated using SSIM and PSNR quality evaluation indicators;
[0148] Gradient information collection: In each iteration, the gradient information of the generator and the discriminator is collected. Where L represents the loss function;
[0149] Learning rate adjustment:
[0150] Using the Adam optimizer, the learning rate adjustment formula is:
[0151]
[0152] Among them, lr t is the learning rate of the tth iteration, β1 and β2 are the hyperparameters of the Adam optimizer, which are set to 0.9 and 0.95 respectively;
[0153] In order to further adaptively adjust the learning rate, the gradient change rate grad is introduced v ar t To dynamically adjust the learning rate:
[0154] 1. t+1 =lr t ·(1+α3·grad v ar t )
[0155] Among them, grad var t is the gradient variance in the tth iteration, and α3 is an adjustment factor used to control the influence of gradient changes on the learning rate;
[0156] Gradient variance calculation:
[0157] Calculate the gradient variance to reflect the stability of the gradient:
[0158]
[0159] Among them, g t,i is the gradient of the i-th parameter at the t-th iteration, N2 is the total number of parameters, μ t is the average value of the gradient;
[0160] Learning rate update: Update the learning rate according to the above formula, and use the new learning rate to update the parameters in the next iteration. This solution dynamically adjusts the learning rate by introducing the gradient variance. Compared with the traditional fixed learning rate or simple learning rate decay strategy, it can more finely control the training process and improve the adaptability and effect of the model on complex image restoration tasks.
[0161] After each iteration, the generated repaired image is collected, and the structural similarity index and peak signal-to-noise ratio PSNR of the repaired image are obtained. The similarity index and peak signal-to-noise ratio PSNR are analyzed and processed to generate a comprehensive quality evaluation index QI, which is used to evaluate the image quality and repair effect, and generate the corresponding learning rate secondary adjustment strategy; specifically, it includes the following contents:
[0162] After each iteration, the resulting inpainted image is collected and the following quality parameters are calculated:
[0163] The structural similarity index SSIM is as follows:
[0164]
[0165] Where x and y are the local windows of the reference image and the repaired image, respectively, and μ x , μ y is the mean, is the variance, σ xy is the covariance, c1 and c2 are constants used to stabilize the calculation;
[0166] The peak signal-to-noise ratio PSNR is as follows:
[0167]
[0168] Among them, MAX I is the maximum value of the image pixels, MSE(x,y) is the mean square error;
[0169] Combining SSIM and PSNR, a comprehensive quality evaluation index QI is generated. The calculation formula is as follows:
[0170]
[0171] Parameter explanation, ω i is a weight factor used to balance the impact of different quality evaluation indicators, where ω1, ω2, ω3, and ω4 correspond to the weights of SSIM, PSNR, FSIM, and NIQE, respectively, and determine the impact of each evaluation indicator on the overall QI value.
[0172] NIQE is a non-reference image quality assessment method that evaluates image quality based on the deviation of natural scene statistical characteristics NSS; its mathematical expression can be simplified as:
[0173]
[0174] Where v represents the feature vector of the test image, v0 is the average value of the feature vector extracted from the reference image library, Σ is the covariance matrix of the feature vector, Σ- 1 is the inverse of the covariance matrix; this formula calculates the Mahalanobis distance between the eigenvector of the test image and the eigenvector of the reference image;
[0175] FSIM stands for FeatureSimilarityIndex. FSIM is a similarity index based on image features, which is used to evaluate the similarity between two images. Its mathematical expression is simplified as follows:
[0176]
[0177] Among them, S L (x,y) is the brightness similarity at position (x,y), S C (x,y) is the contrast similarity at position (x,y), S p (x,y) is the phase consistency at position (x,y); this formula calculates a comprehensive similarity measure by taking into account the image's brightness, contrast, and phase consistency characteristics;
[0178] f(Metric i″′ ) is a complex function, i″′∈{1, 2, 3, 4}, where Metric i″′ When i″′ takes the values of 1, 2, 3, and 4, it represents SSIM, PSNR, FSIM, and NIQE, respectively, and is used to perform nonlinear transformation on each quality assessment indicator. The formula is as follows:
[0179] f(SSIM)=log(1+SSIM)
[0180] f(PSNR) = exp(-PSNR / 100)
[0181]
[0182] g(NIQE) is a normalization function used to adjust the impact of NIQE. x∈NIQE;
[0183] The value range of QI is set to (0,1). When QI is close to 1, it means that the image quality is close to the original image and the restoration effect is good; when QI is close to 0, it means that the image quality is poor and the restoration effect is not good.
[0184] Auxiliary formula:
[0185] Used to compress the NIQE value into the range of (0,1);
[0186] When the QI value increases, it means that the image restoration quality is improved and the image is closer to the visual and structural features of the original image; conversely, a decrease in the QI value indicates that the restoration effect is poor and the model parameters or training strategy need to be adjusted;
[0187] This formula comprehensively considers the influence of multiple image quality evaluation indicators by introducing complex nonlinear transformation functions and normalization functions, and dynamically adjusts the importance of each indicator through weight factors, thus achieving a comprehensive evaluation of the image restoration quality. This design not only improves the accuracy of the evaluation, but also enhances the adaptability of the model to different image restoration tasks.
[0188] According to the changes in these indicators, the learning rates of the generator and discriminator are dynamically adjusted. If the quality evaluation indicators improve slowly or decrease, the learning rate is increased to explore new parameter spaces; if the quality evaluation indicators improve steadily, the learning rate is maintained or moderately reduced to stabilize the training; specifically, the following are included:
[0189] Secondary adjustment of learning rate:
[0190] According to the generated quality evaluation index QI, the learning rate is adjusted twice:
[0191] 1. t+1 =lr t ·(1+β5·(QIt-QItarget))
[0192] Among them, QIt is the quality evaluation index at the tth iteration, QItarget is the target quality evaluation index, and β5 is the adjustment factor used to control the impact of the quality evaluation index on the learning rate;
[0193] The value range of QI (0,1) is divided into three intervals, namely interval 1 (0,0.3); interval 2 [0.3,0.7); interval 3 [0.7,1);
[0194] In interval 1 (0, 0.3), the image quality is poor, and the learning rate needs to be increased to explore new parameters and quickly improve the image restoration effect. The threshold is set to 0.2. When it is lower than this value, the learning rate is urgently increased in order to achieve significant improvement.
[0195] Quantitative content description: The image restoration quality in this interval is poor, and the restoration effect is not good; at this time, both SSIM and PSNR indicators show a significant decline, by 30% and 25% respectively; FSIM and NIQE also show serious degradation of image quality, with FSIM decreasing by 20% and NIQE increasing by 40%; and SSIM and PSNR do not increase by more than 5% or decrease in three consecutive iterations, and the learning rate should be increased; in this case, the learning rate should be significantly increased by 50% to explore new parameter spaces and try to improve the image restoration effect;
[0196] Judgment criteria and rules: Set the threshold to 0.2. When the QI value is lower than 0.2, start the emergency adjustment mechanism. The specific rules are as follows: If the QI value is lower than 0.2 for three consecutive iterations, increase the learning rate by 50% and re-evaluate the changes in SSIM and PSNR. If SSIM and PSNR do not improve significantly in the next five iterations and the improvement does not exceed 10%, further increase the learning rate to 75%.
[0197] Interaction rule description: In the interval where the QI value is lower than 0.3, the interaction changes of each parameter are as follows:
[0198] When SSIM decreases by 30%, PSNR decreases by 25%, FSIM decreases by 20%, and NIQE increases by 40%. This negative correlation between parameters indicates the overall degradation of image quality. The increase of learning rate by 50% aims to find new parameter combinations that can improve image quality through exploration of parameter space.
[0199] Interval 2: [0.3, 0.7), there is room for improvement in image quality; an adjustment strategy is adopted to maintain or slightly increase the learning rate to steadily improve image quality, with a threshold of 0.5 to maintain training stability and continuous improvement;
[0200] Quantitative content description: In the range of QI value [0.3, 0.7), the image restoration quality has improved, but it has not yet reached the ideal state; SSIM and PSNR indicators show slight improvement, increasing by 10% and 15% respectively; FSIM remains stable, and NIQE decreases by 10%. At this time, the learning rate is adjusted and increased by 10% to maintain the stability of training, and the changes in indicators are continued to be observed;
[0201] Judgment criteria and rules, set the threshold to 0.5, and adopt a conservative strategy when the QI value fluctuates around 0.5; the specific rules are as follows: if the QI value fluctuates between 0.45 and 0.55 for five consecutive iterations, keep the current learning rate unchanged; if the QI value is lower than 0.45 or higher than 0.55 for five consecutive iterations, increase or decrease the learning rate by 5% accordingly;
[0202] Interaction rule description: In the interval of QI value [0.3, 0.7), the interactive changes of various parameters are as follows: when SSIM increases by 10%, PSNR increases by 15%, FSIM remains unchanged, and NIQE decreases by 10%; this positive correlation between parameters indicates a gradual improvement in image quality; a moderate increase of 10% in the learning rate is intended to stabilize the current improvement trend and avoid over-adjustment leading to unstable training;
[0203] Interval 3 [0.7, 1) indicates that the image quality is close to ideal. In this interval, the learning rate is reduced to stabilize the training and prevent overfitting. The threshold is set to 0.85. When it exceeds this value, the learning rate is further reduced to ensure continuous optimization and stability of quality.
[0204] Quantitative content description:
[0205] When the QI value is in the interval [0.7,1), the image restoration quality is close to or reaches the ideal state. The SSIM and PSNR indicators show significant improvement, by 20% and 25% respectively. FSIM and NIQE also show significant improvement in image quality, with FSIM increasing by 15% and NIQE decreasing by 30%. At this time, the learning rate should be reduced by 10% to stabilize the training and prevent overfitting;
[0206] Judgment criteria and rules, set the threshold to 0.85, when the QI value exceeds 0.85, start the stabilization strategy; the specific rules are as follows: if the QI value exceeds 0.85 for three consecutive iterations, reduce the learning rate by 10%, and continue to monitor the changes in SSIM and PSNR. If SSIM and PSNR remain stable or continue to improve in the next five iterations, further reduce the learning rate to 15%;
[0207] The interaction rule description shows that in the range where the QI value is higher than 0.7, the interactive changes of the parameters are as follows: when SSIM increases by 20%, PSNR increases by 25%, FSIM increases by 15%, and NIQE decreases by 30%; this positive correlation between parameters indicates a significant improvement in image quality; the learning rate is reduced by 15% to stabilize the current high-quality restoration state and prevent overfitting due to excessively high learning rate.
[0208] Embodiment five:
[0209] Further explanation based on the fourth embodiment, the multi-scale feature guidance module is designed to make full use of the features of the non-damaged area to promote the coordination of the generated area with the undamaged area in structure and texture, and improve the quality and fidelity of the repair result; specifically including the following contents:
[0210] like Figure 4 As shown in the figure, a multi-scale feature guidance module is designed to preserve the details of the non-masked area of the image; assuming that the input image is a mask input Y with a mask m, the module represents the mask image input as a multi-layer feature map instead of compressing it into a single-layer feature;
[0211] Injecting large kernel-based convolution into the multi-scale feature guidance module aims to integrate the advantages of CNN operation and attention mechanism;
[0212] Specifically, the LKA (Large Kernel Attention) structure is used, which uses an expansion rate of d Deep convolution (DW-Conv) extracts local features, then captures long-distance dependencies through a (2d-1)×(2d-1) deep dilated convolution (DW-D-Conv). Finally, 1×1 point-by-point convolution is used to integrate information and adjust the number of channels to enhance the interaction between channels.
[0213] Since LKA focuses on optimizing the feature expression of occluded areas with a wide receptive field, it helps to globally learn regular textures in the frequency domain. In addition, in order to ensure the generalization ability of LKA, a feedforward network 2 is added after the LKA module. Specifically, the feedforward network 2 consists of RMS normalization, 3×3 convolution, Swish activation function, 3×3 convolution, and Dropout.
[0214] Among them, the RMSNorm normalization function is used to improve training stability; the Swish function can better smooth the gradient while retaining the nonlinear characteristics of ReLU, and can also solve the problem that the ReLU function is not zero-centered and the gradient is zero in the negative part.
[0215] Embodiment six:
[0216] Further explanation based on Example 5, this experiment trained and evaluated the model of this article on three different data sets: Celeba-HQ is an extended version of the CelebA data set, which contains high-quality, high-resolution face images. 27,000 images were selected for training, 3,000 for testing and verification, and 20 scene categories were selected for experiments, of which 90,000 images were used for training and 10,000 images were used for quantitative evaluation; a self-made Tibetan thangka data set, including Buddhist thangkas, Dharma protector thangkas, exoteric thangkas and family thangkas, of which 2,500 were used for training and 500 were used for testing and verification, as shown in Table 1;
[0217] Table 1 Settings of Celeba, Facade and self-made thangka datasets
[0218] Dateset Trainingset Validationset Testset Celeba-HQ 27000 1800 1200 Places2 90000 6000 4000 Thangka 2500 300 200
[0219] For quantitative comparison, this embodiment uses various image quality indicators, including the traditional peak signal-to-noise ratio (PSNR), structural similarity index (SSIM), mean absolute error (MAE), and the latest feature-based learning-based perceptual image patch similarity (LPIPS);
[0220] The implementation details are as follows:
[0221] For the first stage of shared codebook learning, the proposed method uses the Adam optimizer (β1 = 0, β2 = 0.9) for optimization, and the batch size is 16;
[0222] In the second phase of image restoration based on codebook prior, Adam (β1=0.9, β2=0.95) is used for optimization, the batch size is 4, the learning rates of the two phases are set to 2e-4 and 3e-4 respectively, and the cosine scheduler is used for decay; the method of this embodiment is implemented using the PyTorch framework and trained using 1 NVIDIA3090 GPU;
[0223] All comparison models are compared on the Celeba-HQ and Places2 datasets. This application also retrains EC, CTSDG, ICT, PUT, and MAT on the self-made Thangka dataset to further discuss the restoration effect;
[0224] Depend on Figure 5 It can be seen that the first-stage network of the proposed model is trained on the Places2 dataset. As the training progresses, the Quantize loss and Adv loss rise briefly, and then stabilize in the oscillation. The L1 loss, Perceptual loss, and Style loss on the right are gradually reduced through continuous training and tuning, and the quality of the generated images can be improved.
[0225] Embodiment seven:
[0226] Further explanation based on Example 6: Figure 6 , Figure 7 and Figure 8 Visual comparison of restoration results of randomly selected test images from Celeba-HQ, Places2, and self-made thangka datasets are shown;
[0227] The proposed model is compared with existing advanced methods on the Celeba dataset. Figure 6 As shown in the figure, the EC and CTSDG restoration methods have incomplete structure prediction when facing large-area defective images, resulting in large-area distortion in the restoration results;
[0228] exist Figure 6 The cheeks and eyes of the characters in rows 3 and 5 in (b) and (c) are missing;
[0229] ICT uses Transformer to reconstruct visual priors. The overall structure of the restoration result is relatively reasonable, but the image restoration details are not perfect.
[0230] like Figure 6 (d) The frames of the repaired glasses in the first and second rows are deformed, and the human eye is asymmetrical. MAT is a large-area defect repair model guided by a mask. It does not work well for small missing areas in the image.
[0231] like Figure 6 In the restoration results of the 4th and 5th rows in (e), the hair and eyes of the characters do not conform to the facial features;
[0232] The P-VQVAE encoder in PUT converts the original resolution image into latent features in a non-overlapping manner, avoiding the cross-information influence, but the understanding of semantic features is insufficient;
[0233] Figure 6 The last two rows in (f) do not integrate the filled area with the surrounding pixels well, the color of the hat is not coordinated, and the details of the glasses are not perfect;
[0234] Compared with the above methods, the proposed algorithm combines the idea of vector quantization and introduces the parallel CSWinTransformer module and the multi-scale feature guidance module, showing a restoration effect with clear edges and natural color transitions. Even in severely damaged areas, the restoration content is semantically reasonable without any inharmonious or abrupt parts.
[0235] Figure 7The restoration effects of each model on the places2 dataset are shown. EC and CTSDG produce blurry and inconsistent boundary artifacts because they cannot capture long-distance features. ICT loses a lot of information during the downsampling process, so the restored horse legs have defects.
[0236] The repair results of MAT and PUT show semantic inconsistency and color differences;
[0237] like Figure 7 The third row of (e) generates a cabinet on the grassland;
[0238] Figure 7 In the fourth row of (f), the background restoration after removing the person results in unnatural reefs;
[0239] This method avoids the loss of image information by learning through shared codebook, thus obtaining richer semantic information and achieving high-fidelity image restoration.
[0240] Figure 8 Comparison chart of repairs of damaged areas of various thangkas. When the EC algorithm faces large-area defects, it is limited by a small receptive field, resulting in large-scale texture blur in the repair results and the inability to reconstruct the image structure.
[0241] When dealing with partially missing areas of a person, the CTSDG algorithm can reconstruct the basic outline of the person by taking advantage of edge information. However, its restoration level is not ideal in terms of material properties and microscopic details.
[0242] from Figure 8 (e) It can be seen that the MAT algorithm still shows strong repair ability when the defect area is large. It repairs the eye area in the second and fourth rows that the first two algorithms cannot repair. However, the eye position is still unreasonable and the face is distorted.
[0243] Visually, after the restoration of these five images by the proposed algorithm, both the structural coherence and the accuracy of texture details are consistent with the original images; therefore, it can be verified that the proposed algorithm is more suitable for images with complex textures and rich colors such as thangkas;
[0244] Since different individuals have different feelings and judgment criteria, specific numerical comparisons can more accurately reflect the subtle differences between good and bad, making the research results more verifiable and reproducible. Four evaluation criteria, PSNR, SSIM, MAE and LPIPS, were selected, and experiments were conducted on Celeba-HQ, Places2 and self-made thangka datasets.
[0245] All test images are uniformly set to a resolution of 256×256, and irregular masks with the same mask ratio are applied to these images; the existing mainstream algorithms such as EC, CTSDG, ICT, MAT, PUT and the algorithm model proposed in this paper are compared and studied, and the specific values of various evaluation indicators are statistically obtained on this basis, as shown in Table 2;
[0246] The results in Table 2 are analyzed to show that, in the Places2 scene dataset and the self-made thangka dataset, the proposed algorithm shows significant advantages in similarity both at the pixel level and the structural level compared with other algorithms; in some cases, there are differences between the objective evaluation index and the intuitive visual observation, which just confirms the limitation of relying on a single objective or subjective evaluation method to measure the quality of image restoration. At the same time, this also strongly proves the rationality and necessity of combining the two evaluation methods for comprehensive evaluation in this paper;
[0247] The following Table 2 shows the objective quantitative comparison of the proposed algorithm with EC, CTSDG, ICT, MAT, and PUT on three datasets with different mask ratios;
[0248] Table 2
[0249]
[0250] 3.4 Ablation study:
[0251] In order to verify the effectiveness of the key components of the method proposed in this application, this application conducts a series of ablation experiments on the self-made thangka dataset; the main experiments include the following:
[0252] (b) The Encoder part of the CDCT model in this paper uses a Conv layer of the same size to replace the Linear layer.
[0253] (c) Parallel CSWinTransformer modules are replaced with the same number of standard Transformer modules.
[0254] (d) Changing the parallel structure between standard self-attention and CSWin attention in the PCT module to a serial one,
[0255] (e) Remove the multi-scale feature guidance module,
[0256] (f) Replace the LKA structure in the multi-scale feature guidance module with the Conv layer,
[0257] (g) realize the complete network structure of this application;
[0258] Table 3 shows the objective evaluation results of the ablation study of different components. Variant 1 and Variant 2 use the encoder derived from VQGAN and the standard Transformer module, which results in excessive information compression and insufficient utilization of local details, affecting the performance of the model. Variant 3 changes the parallel mode of the internal structure of the PCT module to a sequential mode, resulting in a slight decrease in the index.
[0259] Variant 4 and Variant 5 prove that the multi-scale feature guidance module maintains the decoding ability of the potential representation while making full use of the features of the non-masked area; the complete model with the linear residual encoder module, the parallel CSWinTransformer module and the multi-scale feature guidance module has an average increase of 1.741dB and 0.038 in PSNR and SSIM values, and an average decrease of 0.0221 and 0.0053 in LPIPS and MAE values compared with other replacement components; this shows that these improved modules have a positive impact on the quality of the restoration results;
[0260] The following Table 3 is the quantitative ablation analysis of the proposed method on the self-made thangka dataset:
[0261] Table 3
[0262]
[0263] Fig. 9 The visualization results of each component of the model in this paper are given;
[0264] Depend on Fig. 9 As shown in (b), the damaged area of variant 1 lacks consistency with the surrounding area, and there is a difference in light and dark color on the skin of the person's arms, face, and chest; variants 2 and 3 show that the beads in the person's hands are uneven in size, resulting in artifacts; Fig. 9 As shown in (e), after removing the multi-scale feature guidance module, the local effective information of the restoration result is reduced, the character's fingers are affected by the surrounding blue background, the edge structure of the image's eyes is distorted, and the transition is unnatural;
[0265] like Fig. 9 As shown in (g), the effectiveness and superiority of the CDCT algorithm proposed in this paper in dealing with complex color images are verified. This method can achieve more realistic and reasonable restoration effects.
[0266] In the first stage network, the proposed model embeds continuous features into a discrete space with a finite size, i.e., k code vectors. This embodiment conducts an ablation study to understand the impact of the number of code vectors (k) in the codebook on the model performance. Table 4 shows that when the codebook size is 1024 on the Thangka dataset, better results are produced, and the reconstruction quality is more effective, rather than the larger the codebook vector, the more reasonable the data compression.
[0267] Table 4 Effect of different codebook sizes on model performance:
[0268] Codebook size (k) PSNR / dB↑ SSIM↑ LPIPS↓ MAE↓ 512 26.033 0.839 0.0491 0.0250 1024 27.868 0.889 0.0311 0.0208 2048 26.889 0.868 0.0414 0.0216
[0269] This example uses 5 sets of experiments to determine the optimal hyperparameter settings for Attentionhead and Embeddingdimension.
[0270] When the attention head of the PCT module is set to 8 and the embedding dimension is set to 512, the model can better capture the long-distance dependencies in the input sequence, and the four evaluation indicators are significantly improved, while avoiding the embedding dimension being too high to increase the model calculation burden, as shown in Table 5;
[0271] Table 5 Performance of different hyperparameter combinations of PCT module
[0272] Heads Embeddingdims Params(M) PSNR / dB↑ SSIM↑ LPIPS↓ MAE↓ 4 512 53.05 26.684 0.892 0.0420 0.0218 8 512 53.05 27.752 0.908 0.0302 0.0200 16 512 53.05 26.158 0.874 0.0471 0.0231 8 256 20.95 23.487 0.822 0.0884 0.0292 8 768 106.13 26.174 0.875 0.0470 0.0230
[0273] This embodiment proposes an image restoration method that uses a discrete codebook and a Transformer in collaboration, which has multiple new design features;
[0274] First, a linear encoder is used instead of convolution downsampling, and feature blocks are encoded independently to avoid information cross-influence. Different from conventional restoration models, this embodiment uses a codebook to discretize the intermediate features of the encoding model. Second, in order to avoid information loss in the Transformer, the input to the Transformer is not a discrete token, that is, an index, but the features from the encoder.
[0275] At the same time, the discrete tokens are only used as the output of the Transformer. In addition, the design of the parallel CSwinTransformer module improves the accuracy of token prediction and reduces the number of parameters. Subsequently, an additional multi-scale feature guidance module is added to the decoder, which can better preserve the local details of the non-defective area and recover the details from the quantized output of the encoder.
[0276] Through extensive experiments on multiple representative tasks, it is verified that the CDCT method can not only process thangka images with diverse colors and rich semantics, but also effectively repair various defects in natural images; through in-depth ablation research, the effectiveness of the proposed model design is demonstrated; it aims to accurately identify and repair the incomplete parts in thangka images, which serves as a new direction for optimizing image restoration work.
[0277] Embodiment eight:
[0278] A thangka image restoration system, the system is used to execute the method described.
[0279] Embodiment nine:
[0280] A storage medium stores a computer program, which implements the steps of the thangka image restoration method when executed by a processor.
[0281] The above formulas are all dimensionless and numerical calculations. The formula is a formula for the most recent real situation obtained by collecting a large amount of data and performing software simulation. The preset parameters in the formula are set by technicians in this field according to actual conditions.
[0282] The above embodiments may be implemented in whole or in part by software, hardware, firmware or any other combination thereof. When implemented by software, the above embodiments may be implemented in whole or in part in the form of a computer program product. Those skilled in the art may appreciate that the units and algorithm steps of each example described in conjunction with the embodiments disclosed herein may be implemented by electronic hardware, or a combination of computer software and electronic hardware. Whether these functions are performed by hardware or software methods depends on the specific application and design constraints of the technical solution.
[0283] The units described as separate components may or may not be physically separated, and the components shown as units may or may not be physical units, and may be located in one place or distributed on multiple network units. Some or all of the units may be selected according to actual needs to achieve the purpose of the solution of this embodiment.
[0284] The above description is only a specific implementation manner of the present application, but the protection scope of the present application is not limited thereto. Any technician familiar with the technical field can easily think of changes or substitutions within the technical scope disclosed in the present application, which should be included in the protection scope of the present application.
Claims
1. A thangka image restoration method, characterized in that: The specific steps include: Step S1, collecting thangka images containing damaged parts and missing parts, and preprocessing the collected thangka images, and constructing the preprocessed thangka images into an image data set; Step S2, constructing an encoder-decoder structure based on the Transformer model and using it to jointly learn a discrete codebook, inputting the thangka image in the image data set into the constructed encoder, using the encoder to divide the input thangka image into non-overlapping sub-regions of fixed size, and mapping the sub-regions to a continuous latent space representation through a nonlinear transformation to obtain a feature vector; Step S3, introducing a vector quantization codebook, and performing vector quantization on the continuous potential feature vector output by the encoder, wherein the discrete codebook is constructed by using a clustering algorithm, and each vector in the codebook represents a potential space representation of a sub-region in the image, and finally the obtained discrete codebook is used as codebook prior knowledge; Step S4, construct a parallel CSWin resolution Transformer module, which adopts the design of cross-shaped window and local enhanced position encoding, takes the feature vector in step S3 as input, adds additional learnable position embedding to the feature vector to preserve spatial information, and then flattens the feature vector along the spatial dimension to obtain the final input of the module to predict the probability distribution of the next index; Step S5: Use the parallel CSWin resolution Transformer module in step S4 to accurately infer the index of the missing token, and use these indexes to find the corresponding discrete vectors from the discrete codebook obtained in step S3 for image restoration. After completing one restoration attempt, the system will enter an iterative loop; Step S6, after each iteration, collect the generated repaired image, and obtain the structural similarity index and peak signal-to-noise ratio PSNR of the repaired image, and analyze and process the similarity index and peak signal-to-noise ratio PSNR to generate a comprehensive quality evaluation index QI, which is used to evaluate the image quality and the repair effect, and generate a corresponding learning rate secondary adjustment strategy; Step S7, based on the adaptive learning rate adjustment, a multi-scale feature guidance module is designed, which utilizes the features of the non-damaged area to promote the consistency of the generated area with the non-damaged area in structure and texture, thereby improving the quality and fidelity of the repair result; Step S8: During the repair process, dynamically adjust the learning rate of the model according to the comprehensive quality evaluation index QI and the learning rate adjustment strategy generated in step S6 to optimize the repair effect; Step S9: After all iterations are completed, the final restored thangka image is post-processed, including but not limited to image enhancement, color correction and detail optimization, to improve the quality and visual effect of the restored image, and finally the restored thangka image is output.
2. A thangka image restoration method according to claim 1, characterized in that: In the shared codebook learning phase, the system architecture consists of three core components: the codebook encoder E, the codebook decoder G, and a codebook containing K discrete codes When processing the input image When the codebook encoder E first converts the image I t Transformed into a latent representation Z in a high-dimensional space, Represents an image with height H, width W and 3 color channels, H resolution and resolution W resolution represent the vertical and horizontal sizes of the image respectively; H resolution and resolution W resolution are used to describe the actual size of the image; Right now Here d represents the number of dimensions that make up this latent vector; where resolution m-resolution and resolution n-resolution are used to describe the spatial resolution of the latent representation resolution Z-resolution, and m and n represent the height and width of the spatial dimension respectively; Quantize each vector in this spatial latent representation Z to the nearest codeword c in the codebook k , thus obtaining the following vector quantization output Z c and the corresponding code token sequence s∈{0,…,N-1} m′·n′ , and marked as formula (1): s (i,j) =arg min k ‖WITH (i,j) -c k ‖2 Among them, each element It's Z (i,j) The closest codeword found in codebook C; the quantization operation is performed by calculating the distance ||Z (i,j) -c k ||And select the code word corresponding to the minimum distance to achieve; is the output of vector quantization, representing the potential representation Z at position i and resolution j (i,j) quantized to the closest codeword in codebook C; q(Z) is the vector quantization operation that maps each vector in the latent representation Z to the closest codeword in the codebook C; is to find the code in C that matches Z (i,j) The codeword c with the smallest distance k operation; arg min means finding the distance || Z (i,j) -c k ||The smallest codeword c k The index of s (i,j) is an element in the quantized code token sequence, representing the potential representation Z at position i and resolution j (i,j) The index of the codeword to be quantized; Resolution arg min k ‖Z (i,j) -c k ‖2 is found in codebook C with Z (i,j) The codeword c with the smallest Euclidean distance k The operation arg min means finding the Euclidean distance ‖Z (i,j) -c k ‖2The smallest codeword c k The index of c k ∈C represents each codeword c in codebook C k is a predefined vector used to quantize the latent representation Z; Z (i,j) is the vector of the potential representation Z at position i and resolution j; ||Z (i,j) -c k || is Z (i,j) Code word c k The distance between them is the Euclidean distance or other distance metric; ‖Z (i,j) -c k ‖2 is the relationship between Z(i,j) and codeword c k The Euclidean distance between s∈{0,…,N-1} m′·n′ is the quantized code token sequence, where m′·n′ represents the spatial size of the potential representation Z, that is, the total number of vectors contained in Z. Here, m′·n′ refers to the number of elements in the potential representation Z, each element corresponds to a potential vector, and N is the number of codewords in the codebook C; Then, the decoder G is given Z c Reconstruct high-quality image I rec ; The resulting m′·n′ code token sequence s represents a new potential discrete representation, That is, when (i,j) = k, Overall Reconstruction I rec ≈I t The formula is as follows and is marked as formula (2): I rec =G(Z c )=G(q(E(I))) The encoder performs a mapping operation to convert image data of size H×W into a discrete encoding form of scale H / m×W / n; and uses reconstruction loss to enable end-to-end training of the codebook and model.
3. A thangka image restoration method according to claim 2, characterized in that: The codebook encoder E design point includes that the encoder of the shared codebook learning stage is designed to process the input image in a non-overlapping patch manner and through multiple linear residual layers; The codebook prior-based image inpainting stage includes adding additional learnable position embeddings to the feature vector to preserve spatial information, followed by flattening the feature vector along the spatial dimension to obtain the final input of the module; The model uses parallel CSWinTransformer blocks, where each block consists of parallel multi-head self-attention blocks and cross-window attention blocks, and feed-forward layers; the PCT module combines multi-head and cross-window, and the cross-window attention block adds a position encoding mechanism LePE on the linear projection value V to enhance the local inductive bias; The cross-shaped window attention splits the channel into horizontal and vertical stripes, half of the head captures the horizontal stripe attention, and the other half of the head captures the vertical stripe attention; The output of the PCT module passes through a linear layer and is mapped into a probability distribution using a Softmax function, which corresponds to the probability distribution of the K potential vectors in the codebook e.
4. A thangka image restoration method according to claim 3, characterized in that: The PCT module is trained to predict the probability distribution p(s) of the next index i |s <i ), making the training objective equal to minimizing the negative log-likelihood of the data representation; In each iteration, the quality of the generated image is evaluated using SSIM and PSNR quality evaluation indicators; Gradient information collection: In each iteration, the gradient information of the generator and the discriminator is collected. Where L represents the loss function; Learning rate adjustment: Using the Adam optimizer, the learning rate adjustment formula is: Where lrt is the learning rate of the tth iteration, β1 and β2 are the hyperparameters of the Adam optimizer, which are set to 0.9 and 0.95 respectively; In order to further adaptively adjust the learning rate, the gradient change rate grad is introduced v ar t To dynamically adjust the learning rate: lr t+1 =lr t ·(1+α3·grad v ar t ) Among them, grad v ar t is the gradient variance in the tth iteration, and α3 is an adjustment factor used to control the influence of gradient changes on the learning rate; Calculate the gradient variance to reflect the stability of the gradient: Among them, g t,i is the gradient of the i-th parameter at the t-th iteration, N2 is the total number of parameters, μ t is the average value of the gradient.
5. A thangka image restoration method according to claim 4, characterized in that: After each iteration, the generated repaired image is collected, and the structural similarity index and peak signal-to-noise ratio (PSNR) of the repaired image are obtained. The similarity index and peak signal-to-noise ratio (PSNR) are analyzed and processed to generate a comprehensive quality evaluation index (QI). The index is used to evaluate the image quality and the repair effect, and to generate a corresponding secondary adjustment strategy for the learning rate. After each iteration, the resulting inpainted image is collected and the following quality parameters are calculated: The structural similarity index SSIM is as follows: In SSIM(x,y), x and y are the local windows of the reference image and the repaired image respectively, and μ x , μ y is the mean, is the variance, σ xy is the covariance, c1 and c2 are constants used to stabilize the calculation; The peak signal-to-noise ratio PSNR is as follows: In PSNR(x,y), x and y are the local windows of the reference image and the repaired image respectively, and MAX I is the maximum value of the image pixels, MSE(x,y) is the mean square error; Combining SSIM and PSNR, a comprehensive quality evaluation index QI is generated. The calculation formula is as follows: Parameter explanation, ω i is a weight factor used to balance the impact of different quality assessment indicators, where ω1, ω2, ω3, and ω4 correspond to the weights of SSIM, PSNR, FSIM, and NIQE, respectively; f(Metric i″′ ) is a complex function, i″′∈{1, 2, 3, 4}, where Metric i″′ When i″′ takes the values of 1, 2, 3, and 4, it represents SSIM, PSNR, FSIM, and NIQE, respectively, and is used to perform nonlinear transformation on each quality assessment indicator. The formula is as follows: f(SSIM)=log(1+SSIM) f(PSNR) = exp(-PSNR / 100) g(NIQE) is a normalization function used to adjust the impact of NIQE. x∈NIQE; The value range of QI is set to (0,1). When QI is close to 1, it means that the image quality is close to the original image and the restoration effect is good; when QI is close to 0, it means that the image quality is poor and the restoration effect is not good.
6. A thangka image restoration method according to claim 5, characterized in that: When the QI value increases, it means that the image restoration quality is improved and the image is closer to the visual and structural features of the original image; On the contrary, a decrease in QI value indicates that the restoration effect is poor and the model parameters or training strategy need to be adjusted; According to the changes in these indicators, the learning rates of the generator and discriminator are dynamically adjusted. If the quality evaluation indicators improve slowly or decrease, the learning rate is increased to explore new parameter spaces; if the quality evaluation indicators improve steadily, the learning rate is maintained or moderately reduced to stabilize the training; Includes the following: According to the generated quality evaluation index QI, the learning rate is adjusted twice: lr t+1 =lr t ·(1+β5·(QIt-QItarget)) Among them, QIt is the quality evaluation index at the tth iteration, QItarget is the target quality evaluation index, and β5 is the adjustment factor used to control the impact of the quality evaluation index on the learning rate; In interval 1 (0, 0.3), the image quality is poor, and the learning rate needs to be increased to explore new parameters and quickly improve the image restoration effect. The threshold is set to 0.
2. When it is lower than this value, the learning rate is urgently increased in order to achieve significant improvement. In interval 2 [0.3, 0.7), there is room for improvement in image quality. An adjustment strategy is adopted to maintain or slightly increase the learning rate to steadily improve image quality. The threshold is 0.5 to maintain the stability and continuous improvement of training. Interval three [0.7, 1) indicates that the image quality is close to ideal. In this interval, the learning rate is reduced to stabilize the training and prevent overfitting. The threshold is set to 0.
85. When it exceeds this value, the learning rate is further reduced to ensure continuous optimization and stability of quality.
7. A thangka image restoration method according to claim 6, characterized in that: The multi-scale feature guidance module is designed, which utilizes the features of the non-damaged area to promote the consistency of the structure and texture between the generated area and the undamaged area, thereby improving the quality and fidelity of the repair result; specifically, it includes the following contents: Assuming the input image is a mask input Y with mask m, this module represents the mask image input as a multi-layer feature map, injects a large kernel-based convolution in the multi-scale feature guidance module, Use the LKA structure, which uses a dilation rate of d Deep convolution extracts local features, then captures long-distance dependencies through a (2d-1)×(2d-1) deep dilated convolution. Finally, 1×1 point-by-point convolution integrates information and adjusts the number of channels to enhance the interaction between channels. A feedforward network 2 is added after the LKA module, and the feedforward network 2 consists of RMS normalization, 3×3 convolution, Swish activation function, 3×3 convolution and Dropout.
8. A thangka image restoration system, characterized by: The system is used to execute the method according to any one of claims 1 to 7.
9. A storage medium having a computer program stored thereon, characterized in that: When the computer program is executed by a processor, the steps of the thangka image restoration method described in any one of claims 1 to 7 are implemented.
Citation Information
Patent Citations
Image generation system and method
CN113449135A
Diversified image restoration method based on multi-scale features and separation attention
CN116630196A
Remote sensing image saliency detection method based on multi-scale feature aggregation network
CN117809198A
Global character image restoration method and device, and medium
CN118154476A
Thangka image restoration method and system based on multistage adaptive CNN and hybrid Transform, and storage medium
CN118172290A
Cited By
Thangka image segmentation method based on edge feature guidance and detail feature denoising
CN119169296A
Thangka image segmentation method based on edge feature guidance and detail feature denoising
CN119169296B
Image restoration method and device, electronic equipment and storage medium
CN119941574A
Thangka black and white structure line vectorization processing method and system based on deep learning
CN120852156A
A Deep Learning-Based Vectorization Method and System for Black and White Structure Lines in Thangka Painting
CN120852156B
