作为一个更大模块的一部分,我想使用matplotlib保存一系列图像。只有少量的图像(即1-3),所以我试图动态设置plt.subplot中指定的列数。当我尝试对三个图像执行此操作时,一切都很好-我得到了一行3个图像:
然而,当我尝试只使用两张图像时,我会在子画面的右手边得到一张图像:
我提取了原始代码的关键方法,并创建了一个示例(见下文),该示例以与实际代码完全相同的格式向该方法提供图像数组。
为什么我可以得到一行3个图像,但不能得到2个图像?
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('Agg') # suppresses plot
import numpy as np
from PIL import Image, ImageOps
def generate_images(test_input, path_filename):
plt.figure(figsize=(15, 6))
# This configuration works - Gives 3 images
#display_list = [test_input[0], test_input[0], test_input[0]]
#title = ['Test Image 1', 'Test Image 2', 'Test Image 3']
# This configuration does not work - Only gives 1 image on right side
# of subplot
display_list = [test_input[0], test_input[0]]
title = ['Test Image 1', 'Test Image 2']
for i in range(len(title)):
# Here is where I tried to dynamically create my subplot dimensions
plt.subplot(1, len(title), i + 1)
plt.title(title[i])
# Getting the pixel values in the [0, 1] range to plot.
plt.imshow(display_list[i] * 0.5 + 0.5, cmap=plt.get_cmap('gray'))
plt.axis('off')
plt.tight_layout()
plt.savefig(path_filename, dpi=200)
plt.close()
print()
print("Image Shape:",test_input.shape)
print("len(title):",len(title))
# Get Sample Image
file_path = <path to input image>
im = Image.open(file_path)
# Rescale and change from RGB to grayscale
im2 = ImageOps.grayscale(im)
im2 = im2.resize((256,256))
num_array = np.asarray(im2)
# Convert to an array of images
num_array = num_array[np.newaxis,:,:,np.newaxis]
out_path = <path and filename of output image>
generate_images(num_array,out_path)