pythonarraysmatplotlibimshowsave-image

How to save multiple images generated using matplotlib & imshow in a folder


I'm working with matplotlib, specifically its imshow() operation. I have a multi-dimension array generated by random.rand function from NumPy.

data_array = np.random.rand(63, 4, 4, 3)

Now I want to generate images using the imshow() function from matplotlib using every 63 entries of this data array, and even this code below has generated the desired image I wanted.

plt.imshow(data_array[0])  #image constructed for the 1st element of the array

Now I wanted to save all the images produced using the imshow() from the array's entries and save those in a specific folder on my computer with a specific name. I tried with this code below.

def create_image(array):
    return plt.imshow(array, interpolation='nearest', cmap='viridis')


count = 0
for i in data_array:
    count += 63
    image_machine = create_image(i)
    image_machine.savefig('C:\Users\Asus\Save Images\close_'+str(count)+".png")

Using this code, I want to save each image produced using each entry of data_array using the imshow() function and save it to the specific folder 'C:\Users\Asus\Save Images' with a particular name encoding like 1st image will be saved as close_0.png

Please help me in this saving step, I'm stuck here.


Solution

  • You can do the following:

    from pathlib import Path
    
    import matplotlib.pyplot as plt
    import numpy as np
    
    output_folder = "path/to/folder/"
    
    data_array = np.random.rand(63, 4, 4, 3)
    
    for index, array in enumerate(data_array):
        fig = plt.figure()
        plt.imshow(array, interpolation="nearest", cmap="viridis")
        fig.savefig(Path(output_folder, f"close_{index}.png"))
        plt.close()
    

    I have added the plt.close otherwise you will end up with a lot of images simultaneously open.