An image generation method and system based on AI deep learning
By introducing the self-attention mechanism and the LS-C-DCGAN model of the PyTorch framework into GAN, combined with the least squares loss function and SELU activation function, the problems of unstable GAN training and limited image resolution are solved, and high quality is achieved , stable image generation.
Patent Information
- Application Number
- CN202410652253.0
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2024-05-24
- Publication Date
- 2024-10-18
- Estimated Expiration
- 2044-05-24
AI Technical Summary
The existing generative adversarial network (GAN) has problems such as unstable training, lack of unified quantitative evaluation standards, and limited resolution of generated images, making it difficult to generate high-quality and stable images.
The self-attention mechanism is used to extract window features from the image data set, and is added as a constraint to the LS-C-DCGAN model. The generator and discriminator are built through the PyTorch framework, and the least squares loss function and SELU activation function are used. Combining deconvolutional layers and batch normalization, iterative training is performed to improve the stability and quality of image generation.
The self-attention mechanism extracts local and global features of images, improves the details and diversity of image generation, enhances the stability and adaptability of the model, significantly improves the quality and authenticity of the generated images, and solves training instability and resolution limitations. problem.
Smart Images

Figure CN118505838B_ABST
Abstract
Description
Technical Field
[0001] The present invention relates to the field of image processing technology, and in particular to an image generation method and system based on AI deep learning. Background Art
[0002] In recent years, with the rapid development of Internet technology, transmission and storage technology, smart portable devices and entertainment and leisure applications, various image and video resources have emerged in large quantities, greatly enriching people's lives. These image information plays an increasingly important role in daily life and work. However, in some fields, due to the limitations of real scenes and image acquisition tools, the existing image quality still cannot meet our requirements, such as medical diagnosis, satellite remote sensing and traffic monitoring.
[0003] The development of deep learning technology has brought more possibilities to people. People hope that machines can be full of creativity and be able to draw, write poetry, compose music, etc. With the introduction of autoencoders and variational encoders, these ideas have gradually become a reality. The introduction of generative adversarial networks (GANs) has further promoted the development of unsupervised learning. GANs have become an important research direction in the field of deep learning.
[0004] At present, the research and application of GAN are mainly concentrated in the fields of image and vision, such as image style transfer, image denoising and restoration, image synthesis and image super-resolution. GAN introduces the idea of game theory, alternately trains the generator and the discriminator during the training process to learn the feature distribution of the data, learns the feature representation without labeled samples, and uses stochastic gradient descent (SGD) to achieve optimization.
[0005] There are currently several major problems with generative adversarial networks: (1) Training instability. In different network structures, the instability of generated samples still exists, which is one of the main factors restricting the development of GANs. (2) There is a lack of unified quantitative evaluation standards. The current image evaluation standards cannot systematically evaluate the quality of generated samples from multiple aspects. It is more urgent to design a good evaluation standard. (3) The resolution of generated images is limited. Summary of the invention
[0006] In view of this, an embodiment of the present invention aims to provide an image generation method and system based on AI deep learning, wherein the generated adversarial network is relatively stable, the generated pictures are of high quality and are relatively close to real data.
[0007] In a first aspect, an embodiment of the present invention provides an image generation method based on AI deep learning, which includes:
[0008] Collect image datasets for training and prepare image windows required for feature extraction.
[0009] A self-attention mechanism is used to extract window features from the image dataset.
[0010] The LS-C-DCGAN model is built using the PyTorch framework.
[0011] The window features extracted from the self-attention mechanism are added as constraints to the LS-C-DCGAN model.
[0012] The extracted window features are used as training constraints to perform GAN training on the LS-C-DCGAN model.
[0013] Evaluate the quality and diversity of the generated images, and adjust and optimize the model based on the evaluation results.
[0014] The trained LS-C-DCGAN model is applied to image generation tasks in actual scenarios.
[0015] In combination with the first aspect, an embodiment of the present invention provides a first possible implementation manner of the first aspect, wherein collecting an image data set for training and preparing an image window required for feature extraction includes:
[0016] Collect images for training and define the image dataset D = {I1, I2, ..., I n}, where n is the number of images, and each I i Represents an image.
[0017] For each image I i Perform sliding window scanning to scan I in blocks of (H, W) size i Slide the window and extract the local area of the image as the image window. Each image window is represented by P j= (x j ,y j ,H,W), where (x j ,y j ) represents the pixel coordinates of the upper left corner of each image window, and (H, W) represents the height and width of each image window.
[0018] Its technical effect is: by scanning with sliding windows, each image is divided into multiple small local areas, and fine-grained features in the image are captured. Each image window contains local image information, which is used to extract feature details and process complex images. By scanning multiple windows, the feature information of the image is obtained from multiple angles and levels. The extracted image windows contain local information at different positions, providing a more stable and robust feature extraction method and reducing the impact of noise on model training. The extracted image windows serve as the input of the self-attention mechanism, which helps to extract self-attention features from local areas, improve the effect of feature extraction, better process the feature information of local areas, and enhance the model's ability to understand and generate image content.
[0019] In combination with the first aspect, an embodiment of the present invention provides a second possible implementation of the first aspect, wherein the extracting window features from the image dataset using a self-attention mechanism includes:
[0020] A window feature extraction network with a self-attention mechanism is designed, which accepts an image window as input and outputs a feature representation within the window.
[0021] For each image window P j Apply the convolutional layer of the window feature extraction network to obtain a feature map, ϕ (P j )∈R H*W*C , where C is the number of output channels.
[0022] Select another image window P from the image data set k , calculate the self-attention score ,in, ϕ (P j )and ϕ (P k ) are two windows P j and P k The corresponding feature map, ϕ (P j ) ϕ (P k ) T Used to calculate the similarity between two image windows.
[0023] The self-attention score s(P j , P k ) is normalized to obtain the image window P j The self-attention representation α j =softmax j (s(P j , P k )).
[0024] For each image I i , the self-attention representation of each image window is α j Combined into a feature vector Z j ={α1, α2, …, α M}, where M is each image I i The number of windows to extract.
[0025] The technical effect is: by calculating the similarity between image windows, effectively capturing the relationship between image windows, extracting more representative features, and more accurately reflecting the relevance of image content, the self-attention score of each image window is calculated through the self-attention mechanism, and the feature extraction results are further optimized based on local features, helping the model capture the details and global features in the image, improving the quality of the generated image, simplifying the feature processing process, and reducing the computational complexity. The self-attention representation of each image window is combined into a feature vector Z j , forming a global understanding of the entire image, better adapting to complex image scenes, and improving the model's detail expression and diversity when generating images.
[0026] In combination with the first aspect, an embodiment of the present invention provides a third possible implementation of the first aspect, wherein the use of the PyTorch framework to build the LS-C-DCGAN model includes:
[0027] Import the basic modules, optimizers, data processing libraries, data loaders, and tool libraries of the PyTorch library.
[0028] Define the network structure of the generator G and the network structure of the discriminator D.
[0029] The least squares loss function is defined as the loss function of the generator G and the discriminator D.
[0030] Optimizers are defined for the generator G and the discriminator D, respectively.
[0031] A loop training is defined to iteratively train the generator G and the discriminator D.
[0032] The technical effect is: using the PyTorch framework, the network structure of the generator G and the discriminator D is flexibly defined, which facilitates network design and adjustment. The present invention alleviates the training instability problem existing in traditional GAN by defining the least squares loss function as the loss function of the generator and the discriminator, smoothes the confrontation process between the generator and the discriminator, promotes more stable model training, and greatly improves the quality and authenticity of the generated images. By defining a cyclic training process, the generator and the discriminator are iteratively trained, so that the generator and the discriminator continuously improve their performance in mutual confrontation. Through iterative optimization, the quality of the generated images is gradually improved, approaching the distribution of real images.
[0033] In combination with the first aspect, the embodiment of the present invention provides a fourth possible implementation manner of the first aspect, wherein the network structure of the generator G includes:
[0034] The input layer consists of a random noise vector z.
[0035] Several deconvolution layers and several SELU activation layers, repeated convolution transposition, batch normalization and SELU activation.
[0036] Output layer, outputs the generated image.
[0037] Its technical effects are: the setting of the deconvolution layer (convolution transpose layer) is used to gradually restore the spatial resolution of the image, restore the low-resolution feature map to the high-resolution image, ensure the detail quality and resolution of the generated image, use the deconvolution layer multiple times, gradually increase the size of the image, while maintaining the details and quality of the image. Use the SELU activation layer, the SELU activation function has the characteristics of self-normalization, automatically adjusts the mean and variance of the output, avoids gradient vanishing and gradient explosion, improves the stability and efficiency of training, and maintains a good activation distribution in the deep neural network. The batch normalization layer is used to standardize the input data of each batch, accelerate the training process, stabilize the model training, and reduce the internal covariate shift. The output layer uses an appropriate activation function (such as Tanh) to limit the pixel value of the output image to a reasonable range (usually [-1, 1]), ensuring that the generated image has a realistic pixel value distribution.
[0038] In combination with the first aspect, the embodiment of the present invention provides a fifth possible implementation of the first aspect, wherein the network structure of the discriminator D includes:
[0039] The input layer includes a real image or a generated image output by the generator G.
[0040] Several convolutional layers and several SELU activation layers, repeatedly performing convolution, batch normalization, SELU activation and maximum pooling operations.
[0041] Output layer, outputs the authenticity probability of the image.
[0042] Its technical effect is that the discriminator extracts the deep features of the image layer by layer through multi-layer convolution operations, captures the complex patterns and details in the image, and enhances the ability to distinguish between real images and generated images. The SELU activation function has a self-normalization feature, which helps to automatically adjust the mean and variance of the output, avoid gradient vanishing and gradient explosion problems, and improve the stability and efficiency of the discriminator during training. Through the batch normalization layer, the input data of each batch is standardized, the internal covariate shift is reduced, the training process is accelerated, and the convergence speed and generalization ability of the model are improved. The maximum pooling operation is performed after each layer of convolution, which can effectively reduce the size of the feature map and reduce the computational complexity, while retaining important features and enhancing the discriminative ability of the model.
[0043] In combination with the first aspect, an embodiment of the present invention provides a sixth possible implementation of the first aspect, wherein the step of adding the window features extracted from the self-attention mechanism as constraints to the LS-C-DCGAN model includes:
[0044] The random noise vector z and the feature vector Z of the window feature extracted from the self-attention mechanism j A linear transformation is performed to make the two dimensions the same, and the transformed vectors are connected as the input of the input layer.
[0045] The technical effect is that the present invention can fully integrate global randomness and local feature information by linearly transforming and connecting the random noise vector and the window feature, so that the generator can capture the global structure and local details of the image at the same time, and improve the authenticity of the generated image. The self-attention mechanism can capture important local features in the image, and add these features as constraints, so that the generator pays more attention to details when generating images, improves the quality of local features of the generated images, and makes the generated images more delicate and realistic.
[0046] In combination with the first aspect, an embodiment of the present invention provides a seventh possible implementation manner of the first aspect, wherein evaluating the quality and diversity of the generated images, and adjusting and optimizing the model according to the evaluation results includes:
[0047] Calculate the difference in feature distribution between the generated image and the real image.
[0048] Calculate the first recognition score of the generated images to evaluate the diversity and clarity of the generated images.
[0049] Adjust the parameters of the model.
[0050] Adjust the network structure of the generator and discriminator.
[0051] The technical effect is as follows: the present invention quantitatively evaluates the closeness between the generated image and the real image by calculating the difference value of the feature distribution between the generated image and the real image, ensures that the generated image is highly similar to the real image visually, and evaluates the diversity and clarity of the generated image by calculating the initial recognition score of the generated image, ensures that the generated image not only meets the quality standards, but also has diversity in content, and avoids the generated image being too single. According to the evaluation results, the parameters of the model are adjusted, the learning process of the generator and the discriminator is refined, and the model can be adapted to different types of image generation tasks by dynamically adjusting the network structure and parameter settings, optimize the model performance, enhance the model stability and adaptability, and thus ensure the excellent performance of the model in practical applications.
[0052] In a second aspect, an embodiment of the present invention further provides an image generation system based on AI deep learning, which includes:
[0053] The image data collection module is used to collect image data sets for training and prepare image windows required for feature extraction.
[0054] The feature extraction module is used to extract window features from the image dataset using a self-attention mechanism.
[0055] Model building module for building LS-C-DCGAN model using PyTorch framework.
[0056] A model supplement module is used to add the window features extracted from the self-attention mechanism as constraints to the LS-C-DCGAN model.
[0057] The training module is used to perform GAN training on the LS-C-DCGAN model using the extracted window features as training constraints.
[0058] The evaluation and correction module is used to evaluate the quality and diversity of the generated images and adjust and optimize the model based on the evaluation results.
[0059] The application module is used to apply the trained LS-C-DCGAN model to image generation tasks in actual scenarios.
[0060] In a third aspect, an embodiment of the present invention further provides a computer-readable storage medium having a computer program stored thereon, which, when executed by a processor, implements the image generation method based on AI deep learning as described above.
[0061] The beneficial effects of the embodiments of the present invention are:
[0062] The present invention adopts an improved LS-C-DCGAN model, and alternately uses convolution and pooling operations in the generator and discriminator to enhance the learning ability and stability of the network. Among them, the generator structure includes a deconvolution layer (Deconv) and batch normalization (BatchNorm) combined with a scaled exponential linear unit (SELU) activation function, and uses a Tanh activation function in the output layer to make the generated image smoother and more natural; the discriminator structure includes a convolution layer (Conv), a maximum pooling (MaxPool), a batch normalization (BatchNorm) and a SELU activation function, and finally outputs the authenticity probability of the image through a sigmoid activation function, which improves the discriminator's discriminative ability.
[0063] The present invention uses the self-attention mechanism to extract window features from the image dataset and adds the window features as constraints to the generative adversarial network to further improve the details and quality of the generated images. The self-attention mechanism calculates the similarity scores between image windows and extracts the self-attention representation of the image, thus enhancing the global consistency and local details of the generated image.
[0064] The present invention uses the Inception Score (IS) and other image quality evaluation indicators to evaluate the quality and diversity of generated images, ensure the excellent performance of generated images in different aspects, adjust and optimize the model according to the evaluation results, and further improve the quality and diversity of generated images. BRIEF DESCRIPTION OF THE DRAWINGS
[0065] In order to more clearly illustrate the technical solutions of the embodiments of the present invention, the drawings required for use in the embodiments are briefly introduced below. It should be understood that the following drawings only show certain embodiments of the present invention and therefore should not be regarded as limiting the scope. For ordinary technicians in this field, other related drawings can be obtained based on these drawings without creative work.
[0066] Figure 1 This is a flow chart of the image generation method based on AI deep learning of the present invention;
[0067] Figure 2 Schematic diagram of the network structure of the generator G in the image generation method based on AI deep learning of the present invention;
[0068] Figure 3 Schematic diagram of the network structure of the discriminator D in the image generation method based on AI deep learning of the present invention; DETAILED DESCRIPTION
[0069] In order to make the purpose, technical solutions and advantages of the embodiments of the present invention clearer, the technical solutions in the embodiments of the present invention will be clearly and completely described below in conjunction with the drawings in the embodiments of the present invention. Obviously, the described embodiments are part of the embodiments of the present invention, not all of the embodiments. Generally, the components of the embodiments of the present invention described and shown in the drawings here can be arranged and designed in various different configurations.
[0070] Please refer to Figures 1 to 3 The first embodiment of the present invention provides an image generation method based on AI deep learning, which includes: collecting an image data set for training and preparing an image window required for feature extraction; using a self-attention mechanism to extract window features from the image data set; using a PyTorch framework to build an LS-C-DCGAN model; adding the window features extracted from the self-attention mechanism as constraints to the LS-C-DCGAN model; using the extracted window features as training constraints to perform GAN training on the LS-C-DCGAN model; evaluating the quality and diversity of the generated images, and adjusting and optimizing the model according to the evaluation results; and applying the trained LS-C-DCGAN model to image generation tasks in actual scenarios.
[0071] The collecting of image data sets for training and preparing image windows required for feature extraction include: collecting images for training, defining an image data set D = {I1, I2, ..., I n}, where n is the number of images, and each I i Represents an image; for each image I i Perform sliding window scanning to scan I in blocks of (H, W) size i Slide the window and extract the local area of the image as the image window. Each image window is represented by P j= (x j ,y j ,H,W), where (x j ,y j ) represents the pixel coordinates of the upper left corner of each image window, and (H, W) represents the height and width of each image window.
[0072] Its technical effect is: by scanning with sliding windows, each image is divided into multiple small local areas, and fine-grained features in the image are captured. Each image window contains local image information, which is used to extract feature details and process complex images. By scanning multiple windows, the feature information of the image is obtained from multiple angles and levels. The extracted image windows contain local information at different positions, providing a more stable and robust feature extraction method and reducing the impact of noise on model training. The extracted image windows serve as the input of the self-attention mechanism, which helps to extract self-attention features from local areas, improve the effect of feature extraction, better process the feature information of local areas, and enhance the model's ability to understand and generate image content.
[0073] The extracting window features from the image data set using the self-attention mechanism comprises: designing a window feature extraction network of the self-attention mechanism, wherein the window feature extraction network accepts an image window as input and outputs a feature representation within the window; for each image window P j Apply the convolutional layer of the window feature extraction network to obtain a feature map, ϕ (P j )∈R H*W*C , where C is the number of output channels; another image window P is selected from the image data set k , calculate the self-attention score ,in, ϕ (P j )and ϕ (P k ) are two windows P j and P k The corresponding feature map, ϕ (P j ) ϕ (P k ) T Used to calculate the similarity between two image windows; the self-attention score s(P j , P k ) is normalized to obtain the image window P j The self-attention representation α j =softmax j (s(P j , P k )); For each image I i , the self-attention representation of each image window is α j Combined into a feature vector Z j ={α1, α2, …, α M}, where M is each image I i The number of windows to extract.
[0074] The technical effect is: by calculating the similarity between image windows, effectively capturing the relationship between image windows, extracting more representative features, and more accurately reflecting the relevance of image content, the self-attention score of each image window is calculated through the self-attention mechanism, and the feature extraction results are further optimized based on local features, helping the model capture the details and global features in the image, improving the quality of the generated image, simplifying the feature processing process, and reducing the computational complexity. The self-attention representation of each image window is combined into a feature vector Z j , forming a global understanding of the entire image, better adapting to complex image scenes, and improving the model's detail expression and diversity when generating images.
[0075] Among them, the use of the PyTorch framework to build the LS-C-DCGAN model includes: importing the basic modules, optimizers, data processing libraries, data loaders and tool libraries of the PyTorch library; defining the network structure of the generator G and the network structure of the discriminator D; defining the least squares loss function as the loss function of the generator G and the discriminator D; defining optimizers for the generator G and the discriminator D respectively; defining loop training to iteratively train the generator G and the discriminator D.
[0076] Specifically, it includes importing basic modules such as 'torch' and 'torch.nn'. The code includes
[0077] import torch, import the main library of PyTorch, providing tensor operations and automatic differentiation functions,
[0078] import torch.nn as nn, imports PyTorch's neural network module, which contains classes and functions for building various layers and models.
[0079] Import the 'torch.optim' optimizer to define optimization algorithms, including SGD, Adam, etc. The code includes
[0080] import torch.optim as optim;
[0081] Import data processing libraries, including 'torchvision.datasets' and 'torchvision.transforms', for loading and preprocessing image data. The code is
[0082] from torchvision import datasets, transforms, import the torchvision library;
[0083] Import data loaders, including 'torch.utils.data.DataLoader', for batch loading of data, the code is
[0084] from torch.utils.data import DataLoader;
[0085] Import the tool library 'numpy' for array operations and calculations. The code is
[0086] import numpy as np.
[0087] Specifically, in the LS-C-DCGAN model, the least squares loss function is used as the loss function of the generator and the discriminator. The least squares loss function is defined by the 'MSELoss' function of PyTorch. The code is
[0088] criterion = nn.MSELoss().
[0089] Specifically, the Adam optimizer provided by PyTorch is used to define optimizers for the generator G and the discriminator D respectively. The code is
[0090] optimizer_G = optim.Adam(generator.parameters(), lr=0.0002, betas=(0.5, 0.999)),
[0091] optimizer_D = optim.Adam(discriminator.parameters(), lr=0.0002, betas=(0.5, 0.999)).
[0092] Specifically, each iteration includes: switching between real data and fake data generated by the generator; inputting the data into the discriminator for forward propagation, calculating the loss and updating the weights of the discriminator; inputting random noise into the generator to generate fake data, and then inputting the fake data into the discriminator for forward propagation, calculating the loss of the generator and updating the weights of the generator; calculating and recording the loss value and other evaluation indicators.
[0093] The code for the training loop is
[0094] # Training loop
[0095] for epoch in range(num_epochs):
[0096] for i, data in enumerate(dataloader, 0):
[0097] # Update the discriminator
[0098] discriminator.zero_grad()
[0099] real_images = data[0].to(device)
[0100] batch_size = real_images.size(0)
[0101] label = torch.full((batch_size,), 1, dtype=torch.float,device=device)
[0102] output_real = discriminator(real_images).view(-1)
[0103] loss_real = criterion(output_real, label)
[0104] loss_real.backward()
[0105] noise = torch.randn(batch_size, nz, 1, 1, device=device)
[0106] fake_images = generator(noise)
[0107] label.fill_(0)
[0108] output_fake = discriminator(fake_images.detach()).view(-1)
[0109] loss_fake = criterion(output_fake, label)
[0110] loss_fake.backward()
[0111] optimizer_D.step()
[0112] # Update the generator
[0113] generator.zero_grad()
[0114] label.fill_(1)
[0115] output = discriminator(fake_images).view(-1)
[0116] loss_G = criterion(output, label)
[0117] loss_G.backward()
[0118] optimizer_G.step()
[0119] # Record loss and other evaluation metrics
[0120] if i % 100 == 0:
[0121] print('[%d / %d][%d / %d]Loss_D: %.4f Loss_G: %.4f'
[0122] % (epoch, num_epochs, i, len(dataloader),
[0123] loss_D.item(), loss_G.item())). )
[0124] The technical effect is: using the PyTorch framework, the network structure of the generator G and the discriminator D is flexibly defined, which facilitates network design and adjustment. The present invention alleviates the training instability problem existing in traditional GAN by defining the least squares loss function as the loss function of the generator and the discriminator, smoothes the confrontation process between the generator and the discriminator, promotes more stable model training, and greatly improves the quality and authenticity of the generated images. By defining a cyclic training process, the generator and the discriminator are iteratively trained, so that the generator and the discriminator continuously improve their performance in mutual confrontation. Through iterative optimization, the quality of the generated images is gradually improved, approaching the distribution of real images.
[0125] Among them, Figure 2 As shown, the network structure of the generator G includes: an input layer, including a random noise vector z; several deconvolution layers and several SELU activation layers, which repeatedly perform convolution transposition, batch normalization and SELU activation; and an output layer, which outputs the generated image.
[0126] Its technical effects are: the setting of the deconvolution layer (convolution transpose layer) is used to gradually restore the spatial resolution of the image, restore the low-resolution feature map to the high-resolution image, ensure the detail quality and resolution of the generated image, use the deconvolution layer multiple times, gradually increase the size of the image, while maintaining the details and quality of the image. Use the SELU activation layer, the SELU activation function has the characteristics of self-normalization, automatically adjusts the mean and variance of the output, avoids gradient vanishing and gradient explosion, improves the stability and efficiency of training, and maintains a good activation distribution in the deep neural network. The batch normalization layer is used to standardize the input data of each batch, accelerate the training process, stabilize the model training, and reduce the internal covariate shift. The output layer uses an appropriate activation function (such as Tanh) to limit the pixel value of the output image to a reasonable range (usually [-1, 1]), ensuring that the generated image has a realistic pixel value distribution.
[0127] Among them, Figure 3 As shown, the network structure of the discriminator D includes: an input layer, including a real image or a generated image output by the generator G; several convolutional layers and several SELU activation layers, which repeatedly perform convolution, batch normalization, SELU activation and maximum pooling operations; and an output layer, which outputs the authenticity probability of the image.
[0128] Its technical effect is that the discriminator extracts the deep features of the image layer by layer through multi-layer convolution operations, captures the complex patterns and details in the image, and enhances the ability to distinguish between real images and generated images. The SELU activation function has a self-normalization feature, which helps to automatically adjust the mean and variance of the output, avoid gradient vanishing and gradient explosion problems, and improve the stability and efficiency of the discriminator during training. Through the batch normalization layer, the input data of each batch is standardized, the internal covariate shift is reduced, the training process is accelerated, and the convergence speed and generalization ability of the model are improved. The maximum pooling operation is performed after each layer of convolution, which can effectively reduce the size of the feature map and reduce the computational complexity, while retaining important features and enhancing the discriminative ability of the model.
[0129] The step of adding the window features extracted from the self-attention mechanism as constraints to the LS-C-DCGAN model includes: j A linear transformation is performed to make the two dimensions the same, and the transformed vectors are connected as the input of the input layer.
[0130] The generated code for the modified LS-C-DCGAN model includes:
[0131] Generator class Generator(nn.Module):
[0132] def __init__(self, z_dim, feature_dim, img_channels):
[0133] super( Generator , self ).__init__()
[0134] self . fc1 = nn . Linear ( z_dim , 256 );
[0135] self . fc2 = nn . Linear ( feature_dim , 256 ) ;
[0136] self.main = nn.Sequential(
[0137] nn . ConvTranspose2d ( 512 , 256 , 4 , 2 , 1 ) .
[0138] nn . BatchNorm2d ( 256 ) .
[0139] nn.CELL(inplace=True),
[0140] nn . ConvTranspose2d ( 256 , 128 , 4 , 2 , 1 ) .
[0141] nn . BatchNorm2d ( 128 ) .
[0142] nn.CELL(inplace=True),
[0143] nn.ConvTranspose2d(128, 64, 4, 2, 1);
[0144] nn . BatchNorm2d ( 64 ) .
[0145] nn.CELL(inplace=True),
[0146] nn . ConvTranspose2d ( 64 , 32 , 4 , 2 , 1 ) ;
[0147] nn . BatchNorm2d ( 32 ) .
[0148] nn.CELL(inplace=True),
[0149] nn.ConvTranspose2d(32, img_channels, 4, 2, 1);
[0150] nn.Tanh() )
[0152] def forward(self, z, Z_j):
[0153] z = self.fc1(z).view(-1, 256, 1, 1)
[0154] Z_j = self.fc2(Z_j).view(-1, 256, 1, 1)
[0155] h = torch.cat([z, Z_j], 1)
[0156] return self.main(h)
[0157] Discriminator class Discriminator(nn.Module):
[0158] def __init__(self, img_channels):
[0159] super(Discriminator, self).__init__()
[0160] self.main = nn.Sequential(
[0161] nn.Conv2d(img_channels, 64, 4, 2, 1),
[0162] nn.BatchNorm2d(64),
[0163] nn.SELU(inplace=True),
[0164] nn.MaxPool2d(2),
[0165] nn.Conv2d(64, 128, 4, 2, 1),
[0166] nn.BatchNorm2d(128),
[0167] nn.SELU(inplace=True),
[0168] nn.MaxPool2d(2),
[0169] nn.Conv2d(128, 256, 4, 2, 1),
[0170] nn.BatchNorm2d(256),
[0171] nn.SELU(inplace=True),
[0172] nn.MaxPool2d(2),
[0173] nn.Conv2d(256, 512, 4, 2, 1),
[0174] nn.BatchNorm2d(512),
[0175] nn.SELU(inplace=True),
[0176] nn.MaxPool2d(2),
[0177] nn.Conv2d(512, 1, 4, 1, 0),
[0178] nn.Sigmoid() )
[0180] def forward(self, x):
[0181] return self.main(x).view(-1, 1).squeeze(1).
[0182] The technical effect is that the present invention can fully integrate global randomness and local feature information by linearly transforming and connecting the random noise vector and the window feature, so that the generator can capture the global structure and local details of the image at the same time, and improve the authenticity of the generated image. The self-attention mechanism can capture important local features in the image, and add these features as constraints, so that the generator pays more attention to details when generating images, improves the quality of local features of the generated images, and makes the generated images more delicate and realistic.
[0183] The step of evaluating the quality and diversity of the generated images and adjusting and optimizing the model according to the evaluation results includes:
[0184] Calculate the difference between the feature distribution of the generated image and the real image;
[0185] (Specifically, the FID of the generated image and the real image is calculated by fid = fid_score.calculate_fid_given_paths([path_to_real_images, path_to_fake_images],batch_size, device). The lower the FID, the higher the quality of the generated image.)
[0186] Calculate the inception score of the generated image to evaluate the diversity and clarity of the generated image. Specifically, the code for calculating the inception score is is_score, is_std = inception_score(generator, device, batch_size,num_samples). The higher the IS, the better the image quality. Adjust the parameters of the model, including learning rate, batch size, number of layers of the generator and discriminator, etc. Adjust the network structure of the generator and discriminator, including adding or reducing convolutional layers, changing the size of the convolution kernel, adjusting the activation function, etc.
[0187] You can also stabilize the training process and prevent the model from overfitting by adding regularization methods (such as Dropout) and other constraints (such as Gradient Penalty). Repeatedly evaluate the quality and diversity of generated images through adjustment and optimization. Continue to iterate and optimize the model until the quality and diversity of generated images reach a satisfactory level.
[0188] The technical effect is as follows: the present invention quantitatively evaluates the closeness between the generated image and the real image by calculating the difference value of the feature distribution between the generated image and the real image, ensures that the generated image is highly similar to the real image visually, and evaluates the diversity and clarity of the generated image by calculating the initial recognition score of the generated image, ensures that the generated image not only meets the quality standards, but also has diversity in content, and avoids the generated image being too single. According to the evaluation results, the parameters of the model are adjusted, the learning process of the generator and the discriminator is refined, and the model can be adapted to different types of image generation tasks by dynamically adjusting the network structure and parameter settings, optimize the model performance, enhance the model stability and adaptability, and thus ensure the excellent performance of the model in practical applications.
[0189] A second embodiment of the present invention provides an image generation system based on AI deep learning, which includes:
[0190] An image data collection module is used to collect image data sets for training and prepare image windows required for feature extraction;
[0191] A feature extraction module, for extracting window features from the image dataset using a self-attention mechanism;
[0192] Model building module, used to build LS-C-DCGAN model using PyTorch framework;
[0193] A model supplement module is used to add the window features extracted from the self-attention mechanism as constraints to the LS-C-DCGAN model;
[0194] A training module is used to perform GAN training on the LS-C-DCGAN model using the extracted window features as training constraints;
[0195] Evaluation and correction module, used to evaluate the quality and diversity of generated images, and adjust and optimize the model based on the evaluation results;
[0196] The application module is used to apply the trained LS-C-DCGAN model to image generation tasks in actual scenarios.
[0197] A third embodiment of the present invention provides a computer-readable storage medium having a computer program stored thereon, which, when executed by a processor, implements the image generation method based on AI deep learning as described above.
[0198] The embodiments of the present invention are intended to protect an image generation method and system based on AI deep learning, which has the following effects:
[0199] The present invention improves the quality and diversity of generated images by improving the network structure and introducing the self-attention mechanism. It not only has broad prospects in multiple application fields, but also significantly improves the details and information richness of image generation, and enhances the creativity and automation capabilities of the machine. The present invention effectively reduces the cost and difficulty of data annotation and promotes the development and application of generative adversarial networks.
[0200] The computer program product of the AI deep learning-based image generation method and device provided in the embodiments of the present invention includes a computer-readable storage medium storing program code. The instructions included in the program code can be used to execute the method in the previous method embodiment. The specific implementation can be found in the method embodiment, which will not be repeated here.
[0201] Specifically, the storage medium can be a general storage medium, such as a mobile disk, a hard disk, etc. When the computer program on the storage medium is run, it can execute the above-mentioned image generation method based on AI deep learning, thereby improving the quality and diversity of the generated images.
[0202] If the functions are implemented in the form of software functional units and sold or used as independent products, they can be stored in a non-volatile computer-readable storage medium that can be executed by a processor. Based on this understanding, the technical solution of the present invention, or the part that contributes to the prior art, or the part of the technical solution, can be embodied in the form of a software product. The computer software product is stored in a storage medium, including several instructions for a computer device (which can be a personal computer, a server, or a network device, etc.) to perform all or part of the steps of the method described in each embodiment of the present invention. The aforementioned storage medium includes: U disk, mobile hard disk, read-only memory (ROM), random access memory (RAM), disk or optical disk, etc., various media that can store program codes.
[0203] Finally, it should be noted that the above-described embodiments are only specific implementations of the present invention, which are used to illustrate the technical solutions of the present invention, rather than to limit them. The protection scope of the present invention is not limited thereto. Although the present invention is described in detail with reference to the above-described embodiments, ordinary technicians in the field should understand that any technician familiar with the technical field can still modify the technical solutions recorded in the above-described embodiments within the technical scope disclosed by the present invention, or can easily think of changes, or make equivalent replacements for some of the technical features therein; and these modifications, changes or replacements do not make the essence of the corresponding technical solutions deviate from the spirit and scope of the technical solutions of the embodiments of the present invention, and should be included in the protection scope of the present invention. Therefore, the protection scope of the present invention shall be based on the protection scope of the claims.
Claims
1. An image generation method based on AI deep learning, characterized in that: include: Collect image datasets for training and prepare image windows required for feature extraction; Extracting window features from the image dataset using a self-attention mechanism; Use PyTorch framework to build LS-C-DCGAN model; The window features extracted from the self-attention mechanism are added as constraints to the LS-C-DCGAN model; Use the extracted window features as training constraints to perform GAN training on the LS-C-DCGAN model; Evaluate the quality and diversity of the generated images, and adjust and optimize the model based on the evaluation results; Apply the trained LS-C-DCGAN model to image generation tasks in real scenarios; The collecting of image data sets for training and the preparation of image windows required for feature extraction include: Collect images for training and define the image dataset D = {I1, I2, ..., I n }, where n is the number of images, and each I i Represents an image; For each image I i Perform sliding window scanning to scan I in blocks of (H, W) size i Slide the window and extract the local area of the image as the image window. Each image window is represented by P j= (x j ,y j ,H,W), where (x j ,y j ) represents the pixel coordinates of the upper left corner of each image window, and (H, W) represents the height and width of each image window; The extracting window features from the image dataset using the self-attention mechanism comprises: Design a window feature extraction network with a self-attention mechanism, wherein the window feature extraction network accepts an image window as input and outputs a feature representation within the window; For each image window P j Apply the convolutional layer of the window feature extraction network to obtain a feature map, ϕ (P j )∈R H *W*C , where C is the number of output channels; Select another image window P from the image data set k , calculate the self-attention score s(P j , P k )=softmax ,in, ϕ (P j )and ϕ (P k ) are two windows P j and P k The corresponding feature map, ϕ (P j ) ϕ (P k ) T Used to calculate the similarity between two image windows; The self-attention score s(P j , P k ) is normalized to obtain the image window P j The self-attention representation α j =softmax j (s(P j , P k )); For each image I i , the self-attention representation of each image window is α j Combined into a feature vector Z j ={α1, α2, …, α M }, where M is each image I i The number of windows to extract.
2. The image generation method based on AI deep learning according to claim 1, characterized in that: The use of the PyTorch framework to build the LS-C-DCGAN model includes: Import the basic modules, optimizers, data processing libraries, data loaders, and tool libraries of the PyTorch library; Define the network structure of the generator G and the network structure of the discriminator D; Define a least squares loss function as the loss function of the generator G and the discriminator D; Defining optimizers for the generator G and the discriminator D respectively; A loop training is defined to iteratively train the generator G and the discriminator D.
3. The image generation method based on AI deep learning according to claim 2, characterized in that: The network structure of the generator G includes: Input layer, including random noise vector z; Several deconvolution layers and several SELU activation layers, repeating convolution transposition, batch normalization and SELU activation; Output layer, outputs the generated image.
4. The image generation method based on AI deep learning according to claim 3 is characterized in that: The network structure of the discriminator D includes: The input layer includes a real image or a generated image output by the generator G; Several convolutional layers and several SELU activation layers, repeating convolution, batch normalization, SELU activation and maximum pooling operations; Output layer, outputs the authenticity probability of the image.
5. The image generation method based on AI deep learning according to claim 4 is characterized in that: The window features extracted from the self-attention mechanism are added as constraints to the LS-C-DCGAN model, including: The random noise vector z and the feature vector Z of the window feature extracted from the self-attention mechanism j A linear transformation is performed to make the two dimensions the same, and the transformed vectors are connected as the input of the input layer.
6. The image generation method based on AI deep learning according to claim 5, characterized in that: The evaluating the quality and diversity of the generated images and adjusting and optimizing the model according to the evaluation results include: Calculate the difference between the feature distribution of the generated image and the real image; Calculate the initial recognition score of the generated images to evaluate the diversity and clarity of the generated images; Adjust the parameters of the model; Adjust the network structure of the generator and discriminator.
7. An image generation system based on AI deep learning, characterized in that: include: An image data collection module is used to collect image data sets for training and prepare image windows required for feature extraction; A feature extraction module, for extracting window features from the image dataset using a self-attention mechanism; Model building module, used to build LS-C-DCGAN model using PyTorch framework; A model supplement module is used to add the window features extracted from the self-attention mechanism as constraints to the LS-C-DCGAN model; A training module is used to perform GAN training on the LS-C-DCGAN model using the extracted window features as training constraints; Evaluation and correction module, used to evaluate the quality and diversity of generated images, and adjust and optimize the model based on the evaluation results; Application module, used to apply the trained LS-C-DCGAN model to image generation tasks in actual scenarios; The operations performed by the image data collection module include: collecting images for training, defining an image data set D = {I1, I2, ..., I n }, where n is the number of images, and each I i Represents an image; for each image I i Perform sliding window scanning to scan I in blocks of (H, W) size i Slide the window and extract the local area of the image as the image window. Each image window is represented by P j= (x j ,y j ,H,W), where (x j ,y j ) represents the pixel coordinates of the upper left corner of each image window, and (H, W) represents the height and width of each image window; The operations performed by the feature extraction module include: designing a window feature extraction network with a self-attention mechanism, wherein the window feature extraction network accepts an image window as input and outputs a feature representation within the window; for each image window P j Apply the convolutional layer of the window feature extraction network to obtain a feature map, ϕ (P j )∈R H*W*C , where C is the number of output channels; another image window P is selected from the image data set k , calculate the self-attention score s(P j , P k )=softmax ,in, ϕ (P j )and ϕ (P k ) are two windows P j and P k The corresponding feature map, ϕ (P j ) ϕ (P k ) T Used to calculate the similarity between two image windows; the self-attention score s(P j , P k ) is normalized to obtain the image window P j The self-attention representation α j =softmax j (s(P j , P k ));For each image I i , the self-attention representation of each image window is α j Combined into a feature vector Z j ={α1, α2, …, α M }, where M is each image I i The number of windows to extract.
8. A computer-readable storage medium having a computer program stored thereon, characterized in that: When the computer program is executed by a processor, the image generation method based on AI deep learning is implemented as described in any one of claims 1 to 6.
Citation Information
Patent Citations
Near-ground infrared target data set establishment method and device based on generative adversarial network
CN113420639A
Shadow removal method based on Neighbor attention mechanism
CN115496675A
