如何修改plt.subplot代码为单图? (在Github GAN代码中)

How to revise the plt.subplot code to single image? ( In Github GAN code)

我正在使用 github https://github.com/eriklindernoren/Keras-GAN/blob/master/gan/gan.py

中的代码

演示代码在一个图像文件中显示了 25 个生成的图像。 但我想将每张图像以原始尺寸打印为 png 文件。我尝试了几种方法,比如

plt.imshow()

cv2.imwrite()

但是,它们没有用。没有子图图像我无法打印正确的图像。

这是打印图片的部分:

def sample_images(self, epoch):
    r, c = 5, 5
    noise = np.random.normal(0, 1, (r * c, self.latent_dim))
    gen_imgs = self.generator.predict(noise)

    # Rescale images 0 - 1
    gen_imgs = 0.5 * gen_imgs + 0.5
    fig, axs = plt.subplots(r, c)
    cnt = 0

    for i in range(r):
        for j in range(c):
            axs[i,j].imshow(gen_imgs[cnt, :,:,0], cmap='gray')
            axs[i,j].axis('off')
            cnt += 1
    fig.savefig("images/%d.png" % epoch)
    plt.close()

非常感谢。

您正在使用

创建一个包含 25 个子图的图形
fig, axs = plt.subplots(5, 5)

将其替换为 fig, ax = plt.subplots() 以创建具有 1 组轴的图形。如果您希望 25 张图像中的每一张都在它自己的图中,这也需要进入循环。此外,您还需要将对 savefig 的调用也移动到循环中:

def sample_images(self, epoch):
    r, c = 5, 5
    noise = np.random.normal(0, 1, (r * c, self.latent_dim))
    gen_imgs = self.generator.predict(noise)

    # Rescale images 0 - 1
    gen_imgs = 0.5 * gen_imgs + 0.5

    cnt = 0

    for i in range(r):
        for j in range(c):
            fig, ax = plt.subplots()
            ax.imshow(gen_imgs[cnt, :,:,0], cmap='gray')
            ax.axis('off')
            cnt += 1
            fig.savefig("images/%d.png" % epoch)
            plt.close()