如何以图像形式保存CNN模型的输出(预测)? [英] How to save output (prediction) of the CNN model in the form of an image?
问题描述
我有一个名为 Downloaded
的文件夹,其中包含必须由受过训练的CNN模型进行预测的图像.
I have a folder named Downloaded
which contain images on which prediction has to be made by the trained CNN model.
以下是导入图像的代码:
Below is the code for importing images:
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)
现在,以下代码有助于对这些图像进行预测:
Now, the below code helps to make predictions on these images:
predictions = model.predict(images)
最后,对于每个图像,预测以图像和图形的形式显示.
Finally, the predictions are shown in the form of an image and a graph, for each image.
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()
我想将此输出保存为图像形式.
I want to save this output in the form of image.
为此,我使用以下代码:
For that, I use the below code:
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'
能否请您说出如何将输出保存在图像中?
Could you please tell how to save this output in the for of images?
PS:以下是图像
包含的内容:
PS: Below is what images
contain:
出[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]],
[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
If you want to save the array as image, you need to provide the array to imsave
plt.imsave('filename.png', images[i // 2])
如果要将其中包含imshow图的matplotlib图形保存到文件中,应使用 savefig
.
If you want to save the matplotlib figure with the imshow plot in it to a file you should use savefig
.
fig.savefig("filename.png")
这篇关于如何以图像形式保存CNN模型的输出(预测)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!