我有一个名为 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:以下是图像
包含的内容:
Out[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. ]],...................
最佳答案
如果要将数组保存为图像,则需要将数组提供给imsave
plt.imsave('filename.png', images[i // 2])
如果您想将包含 imshow 图的 matplotlib 图形保存到文件中,您应该使用 savefig
。
fig.savefig("filename.png")
关于python - 如何以图像的形式保存CNN模型的输出(预测)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52620222/