Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Matplotlib imsave() method

Matplotlib imsave() method

The imsave() method is a function in the Matplotlib library used to save image data to disk.

With the imsave() method we can easily save generated images to a directory we specify.

The imsave() method supports saving images in multiple image formats, such as PNG, JPEG, BMP, etc.

The syntax of the imsave() method is as follows:

matplotlib.pyplot.imsave(fname, arr, **kwargs)

Parameter Description:

The following is a simple example of using the imsave() method to save an image:

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

Create a 2D image data

img_data

=

np.

random

.

random

(

(

100

,

100

)

)

Displays an image

plt.

imshow

(

img_data

)

Save the image to disk

plt.

imsave

(

'runoob-test.png'

,

img_data

)

In the example above we used the imsave() method to save this image to the current directory with the filename runoob-test.png。

Since no image format was specified, the Matplotlib library saves it as a PNG file by default.

Open the current directory and you will find a runoob-test.png file, as shown below:

The following example demonstrates how to use the imsave() method to save a grayscale image and a color image to the current directory:

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

Create a grayscale image

img_gray

=

np.

random

.

random

(

(

100

,

100

)

)

Create a color image

img_color

=

np.

zeros

(

(

100

,

100

,

3

)

)

img_color

[

:

,

:

,

0

]

=

np.

random

.

random

(

(

100

,

100

)

)

img_color

[

:

,

:

,

1

]

=

np.

random

.

random

(

(

100

,

100

)

)

img_color

[

:

,

:

,

2

]

=

np.

random

.

random

(

(

100

,

100

)

)

Display the grayscale image

plt.

imshow

(

img_gray

,

cmap

=

'gray'

)

Save the grayscale image to disk

plt.

imsave

(

'test_gray.png'

,

img_gray

,

cmap

=

'gray'

)

Display the color image

plt.

imshow

(

img_color

)

Save the color image to disk

plt.

imsave

(

'test_color.jpg'

,

img_color

)

In the example above we used the numpy.random module to create a grayscale image and a color image respectively, then used the imshow() method to display these two images.

Next, we used the imsave() function to save these two images to the current directory, with the filenames test_gray.png and test_color.jpg。

When saving the grayscale image, we used the cmap parameter to save it in grayscale image format.

When saving the color image, we did not specify an image format, and the Matplotlib library saves it as a JPEG file by default.