作為更大模塊的一部分,我想使用 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)
uj5u.com熱心網友回復:
繪制了這兩個影像,由于某種原因,當您要使用時出現問題:plt.tight_layout().
添加所有軸后嘗試呼叫此函式

觀察我如何在 for 回圈之后呼叫函式,這應該可以解決你的問題

您可以在以下鏈接中獲得有關此函式的更多資訊: matplotlib.pyplot.tight_layout
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/438495.html
標籤:Python matplotlib
