我有一个名为Downloaded
的文件夹,其中包含必须由经过训练的CNN模型进行预测的图像。
以下是导入图像的代码:
import os
images = []
for filename in os.listdir("downloaded"):
img = Image.open(os.path.join("downloaded", filename))
img = img.resize((32, 32))
plt.imshow(img)
plt.show()
img = np.array(img) / 255
images.append(img)
现在,以下代码有助于对这些图像进行预测:
predictions = model.predict(images)
最后,对于每个图像,预测以图像和图形的形式显示。
fig, axs = plt.subplots(9, 2, figsize=(10, 25))
axs = axs.ravel()
for i in range(18):
if i%2 == 0:
axs[i].axis('off')
axs[i].imshow(images[i // 2])
axs[i].set_title("Prediction: %s" % id_to_name[np.argmax(predictions[i // 2])])
else:
axs[i].bar(np.arange(65), predictions[i // 2])
axs[i].set_ylabel("Softmax")
axs[i].set_xlabel("Labels")
plt.show()
我想以图像形式保存此输出。
为此,我使用以下代码:
fig, axs = plt.subplots(9, 2, figsize=(10, 25))
axs = axs.ravel()
for i in range(18):
if i%2 == 0:
axs[i].axis('off')
axs[i].imshow(images[i // 2])
axs[i].set_title("Prediction: %s" % id_to_name[np.argmax(predictions[i // 2])])
plt.imsave('"Prediction: %s" % id_to_name[np.argmax(predictions[i // 2])]',axs[i])
else:
axs[i].bar(np.arange(65), predictions[i // 2])
axs[i].set_ylabel("Softmax")
axs[i].set_xlabel("Labels")
plt.show()
但是,出现以下错误:
AttributeError: 'AxesSubplot' object has no attribute 'shape'
能否请您说出如何将输出保存在图像中?
PS:images
包含以下内容:
出[94]:
[array([[[1。,0.85882353,0.85882353], [1。 ,0.04313725,0.03921569], [1。 ,0.04313725,0.03921569], ..., [1。 ,0.04313725,0.03921569], [1。 ,0.03529412,0.03137255], [1。 ,0.76862745,0.76470588]],
[[1. , 0. , 0. ], [1. , 0. , 0. ], [1. , 0. , 0. ], ..., [1. , 0. , 0. ], [1. , 0. , 0. ], [1. , 0. , 0. ]],...................
答案 0 :(得分:1)
如果要将数组另存为图像,则需要将数组提供给imsave
plt.imsave('filename.png', images[i // 2])
如果要将其中包含imshow图的matplotlib图形保存到文件中,应使用savefig
。
fig.savefig("filename.png")
答案 1 :(得分:0)
我能够使用以下代码保存图像:
for i in range(len(images)*2):
finalPrediction.append(id_to_name[np.argmax(predictions[i // 2])])
plt.imsave(('testo/ {}.jpg'.format(str(i // 2)+id_to_name[np.argmax(predictions[i // 2])])),images[i // 2])