python - 尝试使用 Keras Sequential 向图像添加噪声时图像尺寸不匹配

标签 python tensorflow keras generative-adversarial-network

要在您的系统上重新创建此问题,请找到源代码和数据集 here

我在尝试什么?
我正在尝试创建一个简单的 GAN(生成对抗 N/w),尝试使用一些 ImageNet 图像对黑白图像重新着色。


我遵循什么流程?
我拍摄了一些狗图像,它们存储在文件夹 ./ImageNet/dogs/ 目录中。使用 Python 代码,我创建了另外 2 个转换步骤

  1. 将狗图像转换为 244 x 244 分辨率并保存在 ./ImageNet/dogs_lowres/
  2. 狗低分辨率。将图像转换为灰度并保存在 ./ImageNet/dogs_bnw/
  3. 将低分辨率 BnW 图像输入 GAN 模型并生成彩色图像。

我被困在哪里了?
我一直致力于理解如何使用图像尺寸/形状。 我收到这样的错误:

ValueError: `logits` and `labels` must have the same shape, received ((32, 28, 28, 3) vs (32, 224, 224)).

这是生成器和鉴别器的代码:

# GAN model for recoloring black and white images
generator = Sequential()
generator.add(Dense(7 * 7 * 128, input_dim=100))
generator.add(Reshape((7, 7, 128)))
generator.add(Conv2DTranspose(64, kernel_size=5, strides=2, padding='same'))
generator.add(Conv2DTranspose(32, kernel_size=5, strides=2, padding='same'))
generator.add(Conv2DTranspose(3, kernel_size=5, activation='sigmoid', padding='same'))

# Discriminator model
discriminator = Sequential()
discriminator.add(Flatten(input_shape=(224, 224, 3)))
discriminator.add(Dense(1, activation='sigmoid'))

# Compile the generator model
optimizer = Adam(learning_rate=0.0002, beta_1=0.5)
generator.compile(loss='binary_crossentropy', optimizer=optimizer)

# Train the GAN to recolor images
epochs = 10000
batch_size = 32

训练循环如下:

for epoch in range(epochs):
    idx = np.random.randint(0, bw_images.shape[0], batch_size)
    real_images = bw_images[idx]

    noise = np.random.normal(0, 1, (batch_size, 100))
    generated_images = generator.predict(noise)

    # noise_rs = noise.reshape(-1, 1)
    g_loss = generator.train_on_batch(noise, real_images)

    if epoch % 100 == 0:
        print(f"Epoch: {epoch}, Generator Loss: {g_loss}")

错误在哪里? 我在线收到错误:
g_loss = Generator.train_on_batch(noise, real_images)

当我检查噪声和 real_images 对象的形状时,我得到的是:

real_images.shape
(32, 224, 224)
noise.shape
(32, 100)

感谢任何帮助/建议。

最佳答案

generator 输出 [32 28 28 3],而它正在获取形状为 [32 224 224] 的目标。目标有两个区别:它是灰度而不是彩色,并且具有更大的尺寸。

我假设提供给生成器的目标应该是彩色而不是灰度。您可以使用以下方法加载彩色图像并调整其大小:

def load_images_color(directory):
    images = []
    for filename in os.listdir(directory):
        img_path = os.path.join(directory, filename)
        img = cv2.imread(img_path)
        img = cv2.resize(img, (224, 224))  # Resize images to 224x224
        img = img.astype('float32') / 255.0  # Normalize pixel values
        images.append(img)
    return np.array(images)

# Load colour images
cl_images = load_images_color('./ImageNet/dogs')

...

for epoch in range(epochs):
    ...
        
    cl_real = cl_images[idx]
    #Resize colour images to match generator output shape
    cl_real_small = []
    for im in cl_real:
        cl_real_small.append( cv2.resize(im, (28, 28)) )
    cl_real_small = np.array(cl_real_small)
    
    ...

    g_loss = generator.train_on_batch(noise, cl_real_small)

关于python - 尝试使用 Keras Sequential 向图像添加噪声时图像尺寸不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77730831/

相关文章:

python - 获取稀疏矩阵中每个元素的日志

python - `tf.train.Saver`收集变量保存在哪里?

python - Tensorflow 是否会针对每个 eval() 调用重新运行?

python - 为什么 tensorflow 在多次训练 Estimator 时说 Tensor 不是该图的元素?

python - 为什么在 CUDA 内核中没有断点的情况下执行相同的程序时,cuda-gdb 比 gdb 慢很多?

python - ValueError : Shapes (16, ) 和 (1, 16) 在 tensorflow1.0 中不兼容

python - 为什么 Django 表单在波斯语中显示 UnicodeEncodeError?

c++ - 实现结构化张量

python - Actor-Critic 模型永远不会收敛

python - 为什么对 `fit` 的第二个 `GridSearchCV` 调用会无休止地工作?