使用py语言编写一个GAN生成图片程序的代码加上html编写的用户界面
时间: 2024-06-08 09:07:44 浏览: 94
以下是使用Python编写的一个简单的GAN生成图像程序,以及使用HTML和JavaScript编写的用户界面,用户可以通过该界面与模型进行交互并生成图像。注意,这只是一个简单的示例代码,实际应用中可能需要更复杂的模型和界面设计。
Python代码:
```
import tensorflow as tf
import numpy as np
# 定义生成器模型
def build_generator(latent_dim):
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(128 * 7 * 7, activation="relu", input_dim=latent_dim))
model.add(tf.keras.layers.Reshape((7, 7, 128)))
model.add(tf.keras.layers.Conv2DTranspose(128, (4,4), strides=(2,2), padding="same", activation="relu"))
model.add(tf.keras.layers.Conv2DTranspose(128, (4,4), strides=(2,2), padding="same", activation="relu"))
model.add(tf.keras.layers.Conv2D(1, (7,7), activation="sigmoid", padding="same"))
return model
# 定义判别器模型
def build_discriminator():
model = tf.keras.Sequential()
model.add(tf.keras.layers.Conv2D(64, (3,3), strides=(2,2), padding="same", input_shape=(28,28,1)))
model.add(tf.keras.layers.LeakyReLU(alpha=0.2))
model.add(tf.keras.layers.Dropout(0.5))
model.add(tf.keras.layers.Conv2D(64, (3,3), strides=(2,2), padding="same"))
model.add(tf.keras.layers.LeakyReLU(alpha=0.2))
model.add(tf.keras.layers.Dropout(0.5))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(1, activation="sigmoid"))
return model
# 定义GAN模型
def build_gan(generator, discriminator):
discriminator.trainable = False
model = tf.keras.Sequential()
model.add(generator)
model.add(discriminator)
model.compile(loss="binary_crossentropy", optimizer="adam")
return model
# 加载MNIST数据集
(x_train, _), (_, _) = tf.keras.datasets.mnist.load_data()
x_train = np.expand_dims(x_train, axis=-1)
x_train = x_train.astype("float32") / 255.0
# 定义模型参数
latent_dim = 100
epochs = 50
batch_size = 128
# 创建模型
generator = build_generator(latent_dim)
discriminator = build_discriminator()
gan = build_gan(generator, discriminator)
# 训练模型
for epoch in range(epochs):
for batch in range(x_train.shape[0] // batch_size):
noise = np.random.normal(size=(batch_size, latent_dim))
fake_images = generator.predict(noise)
real_images = x_train[np.random.randint(0, x_train.shape[0], size=batch_size)]
x = np.concatenate([real_images, fake_images])
y = np.zeros(2 * batch_size)
y[:batch_size] = 0.9
discriminator.trainable = True
discriminator.train_on_batch(x, y)
noise = np.random.normal(size=(batch_size, latent_dim))
y = np.ones(batch_size)
discriminator.trainable = False
gan.train_on_batch(noise, y)
# 生成图像
noise = np.random.normal(size=(1, latent_dim))
image = generator.predict(noise)[0]
image = np.squeeze(image)
image = (image * 255.0).astype("uint8")
# 保存图像
tf.keras.preprocessing.image.save_img("generated_image.png", image)
```
HTML代码:
```
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>GAN生成图像</title>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<style>
.container {
margin: 20px;
}
.image {
margin-top: 20px;
border: 1px solid black;
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<div id="app" class="container">
<h1>GAN生成图像</h1>
<div>
<button @click="generateImage">生成新图像</button>
</div>
<img class="image" :src="generatedImage" v-if="generatedImage">
</div>
<script>
new Vue({
el: '#app',
data: {
generatedImage: ''
},
methods: {
generateImage() {
fetch('/generate-image')
.then(response => response.json())
.then(data => {
this.generatedImage = data.image;
});
}
}
});
</script>
</body>
</html>
```
在上述代码中,我们使用Vue.js编写了一个简单的用户界面,该界面包含一个按钮和一个显示图像的元素。当用户点击按钮时,界面会通过异步请求向服务器发送一个请求,服务器会生成一张新的图像并将其返回,界面则会显示该图像。注意,我们使用了Flask框架来实现服务器端的代码,具体实现方式可以参考Flask官方文档。
完整的Python代码和HTML代码可以在以下链接中找到:
https://github.com/LinghengMeng/GAN-Image-Generator
阅读全文