简体   繁体   中英

How to save output (prediction) of the CNN model in the form of an image?

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()

But, comes up with the below error:

AttributeError: 'AxesSubplot' object has no attribute 'shape'

Could you please tell how to save this output in the for of images?

PS: Below is what images contain:

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. ]],................... 

If you want to save the array as image, you need to provide the array to imsave

plt.imsave('filename.png', images[i // 2])

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")

I was able to save the images using the below code:

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM