# Matplotlib tutorial 05 --- operating images

2022-04-23 15:56:00 KX-Lau

# Tools -matplotlib

Use matplotlib Can draw beautiful graphics .

stay matplotlib Read from 、 Generating and printing images is very simple .

## Save image

Import matplotlib

``````import matplotlib
import matplotlib.pyplot as plt
``````

Saving graphics to disk is very simple , Just call savefig() function , And pass the saved name of the drawing . The graphics formats available depend on the graphics used .

``````plt.plot(x, x**2)
plt.savefig('my_square_function.png', transparent=True)
`````` Just import matplotlib.image modular , And call imread() function , And pass the file name as a parameter , The image data will be displayed in numpy Array returns . Now read the square function saved before .

``````import matplotlib.image as mpimg

print(img.shape, img.dtype)
``````
``````(288, 432, 4) float32
``````

The above results show that the loaded image is a 288×432 Of , Each pixel is represented by a four element array ： Red 、 green 、 Blue and alpha, Stored as 0 To 1 Between 32 Bit floating point . Now call imshow() function .

``````plt.imshow(img)
plt.show()
`````` When displaying an image , It's better to hide the axis display .

``````plt.imshow(img)
plt.axis('off')
plt.show()
`````` ## Generate the image

It's also easy to generate an image .

``````import numpy as np
img = np.arange(100*100).reshape(100, 100)
print(img)
plt.imshow(img)
plt.show()
``````
``````[[   0    1    2 ...   97   98   99]
[ 100  101  102 ...  197  198  199]
[ 200  201  202 ...  297  298  299]
...
[9700 9701 9702 ... 9797 9798 9799]
[9800 9801 9802 ... 9897 9898 9899]
[9900 9901 9902 ... 9997 9998 9999]]
`````` Because no RGB Level ,imshow() The function automatically maps the value to the color gradient , By default , Color gradient from blue （ Low value ） Turn red （ High value ）, But you can choose other colors .

``````plt.imshow(img, cmap='hot')
plt.show()
`````` You can also directly generate a RGB Images .

``````img = np.empty((20, 30, 3))
img[:, :10] = [0, 0, 0.6]
img[:, 10:20] = [1, 1, 1]
img[:, 20:] = [0.6, 0, 0]
plt.imshow(img)
plt.show()
`````` because img The array is very small （20×30）, When imshow() When the function is displayed , Will increase the image to figure Size . Stretch the original image , A blank space is left between the original pixels . By default ,imshow() The function shades each blank pixel with the color of the nearest non blank pixel . This will produce a pixelated image . Different interpolation methods can also be used , Such as bilinear interpolation to fill the blank pixels , But this can lead to blurred edges , It may be better in some cases .

``````plt.imshow(img, interpolation='bilinear')
plt.show()
`````` https://yzsam.com/2022/04/202204231549498258.html