To use python for digital image processing, you must install the Pillow package. Although Python comes with a PIL (python images library), this library has stopped updating, so use Pillow, which is developed from PIL.
pip install Pillow
1. Opening and displaying of pictures
from PIL import Image
img=Image.open('d:/dog.png')
img.show()
Although Pillow is used, it is a fork of PIL, so import it from PIL. Use the open() function to open the picture, and use the show() function to display the picture.
This kind of picture display method is to call the picture browser that comes with the operating system to open the picture. Sometimes this method is not convenient, so we can also use another method to let the program draw the picture.
from PIL import Image
import matplotlib.pyplot as plt
img=Image.open('d:/dog.png')
plt.figure("dog")
plt.imshow(img)
plt.show()
Although this method is more complicated, it is recommended to use this method. It uses a matplotlib library to draw pictures for display. matplotlib is a professional drawing library, which is equivalent to the plot in matlab. You can set multiple figures, set the title of the figure, and even use subplot to display multiple pictures in one figure. matplotlib can be installed directly
pip install matplotlib
The figure is with axis by default, if there is no need, we can turn it off
plt.axis('off')
After opening the picture, you can use some properties to view the picture information, such as
print img.size #Picture size
print img.mode #Picture mode
print img.format #Picture format
The display result is:
(558,450)
RGBA
PNG
Second, the preservation of pictures
img.save('d:/dog.jpg')
Just one line of code, very simple. This line of code can not only save the image, but also convert the format. In this example, the original png image is saved as a jpg image.
Recommended Posts