[英]How to save output (prediction) of the CNN model in the form of an image?
我有一个名为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. ]],...................
如果要将阵列另存为图像,则需要提供阵列以进行imsave
plt.imsave('filename.png', images[i // 2])
如果要将其中包含imshow图的matplotlib图保存到文件中,则应使用savefig
。
fig.savefig("filename.png")
我能够使用以下代码保存图像:
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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.