In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces how to use the Pillow library of image processing in Python. It is very detailed and has a certain reference value. Friends who are interested must finish it!
Foreword:
Image processing is a commonly used technology. Python has a rich third-party extension library. Pillow is the most commonly used image processing library in Python3, and the highest version is 5.2.0. Python2 uses the Pil library, and the two are used in much the same way, except that the references to the classes are different.
Note: the Pil library and Pillow cannot exist in the same environment at the same time, if you have already installed the Pil library, please uninstall it.
Install Pillow using pip:
> pip install Pillow 1. Create an image instance using Image.open ()
Image is the most commonly used class for Pillow, and it can create image instances in a variety of ways.
"from PIL import Image" imports the Image module. Then the image file can be loaded through the open function in the Image class, and the open function will automatically determine the image format by specifying the location of the file. If successful, the open function returns an Image object; failure to load the file will cause an IOError exception.
1. Create an Image object from a file
Creating Image image objects from files is the most common method
Example: create an Image image object from a file
From PIL import Imageimage = Image.open ('python-logo.png') # create an image instance # View the properties of the image instance print (image.format, image.size, image.mode) image.show () # display the image
Code interpretation:
Instance attribute description:
Format image format
(width, height) tuples of size images
Mode common mode, default RGB true color image; L is grayscale image; CMYK printing color; RGBA true color image with transparency; YCbCr color video format; LAB L * a * b color space; HSV, etc.
The show () method displays an image using the system's default picture viewer, which is generally used for debugging
two。 Read from an open file
You can read from the file object instead of the file name, but the file object must implement the read (), seek (), and tell () methods and open in binary mode.
Example: reading an image from a file object
From PIL import Imagewith open ("hopper.ppm", "rb") as fp: im = Image.open (fp) 2. Read from a string binary stream
To read an image from string data, use the io class:
Import iofrom PIL import Imageim = Image.open (io.StringIO (buffer))
Note: rewind the file (using seek (0)) before reading the image header.
3. Read from PIL import TarIOfp = TarIO.TarIO ("Imaging.tar", "Imaging/test/lena.ppm") im = Image.open (fp) from tar file. Read and write image 1. Format conversion and save the image
The save function in the Image module can save pictures, and unless you specify a file format, the file extension is the file format.
Import osfrom PIL import Imageimage_path='python-logo.png' # Picture location f, e = os.path.splitext (image_path) # get the file name and suffix outfile = f + ".jpg" if image_path! = outfile: try: Image.open (image_path) .save (outfile) # modify the file format except IOError: print ("cannot convert", image_path)
Note: if your picture mode is RGBA, then there will be an exception, because RGBA means red, green, blue, Alpha color space, Alpha refers to transparency. JPG does not support transparency, so either discard Alpha or save it as a .png file. The solution is to convert the picture format:
Image.open (image_path) .convert ("RGB") .save (outfile) # convert to RGB format, discard Alpha
The save () function takes two arguments, and if the file name does not specify the image format, then the second parameter is required, which specifies the image format.
two。 Create thumbnails
Image.thumbnail (size) is used to create thumbnails, and size is the width and length tuple of thumbnails.
Example: create a thumbnail
Import osfrom PIL import Imageimage_path = 'python-logo.png' # picture location size = (128,128) # file size f, e = os.path.splitext (image_path) # get the file name and the suffix outfile = f + ".thumbnail" if image_path! = outfile: try: im = Image.open (image_path) im.thumbnail (size) # set the thumbnail size im.save (outfile JPEG) except IOError: print ("cannot convert", image_path)
Note: an exception occurs, as in the previous example, convert ("RGB") converts the picture mode.
Note: Pillow does not decode or raster data unless necessary. When you open a file, Pillow uses the file header to determine the file format, size, mode and other data, and the rest of the data is not processed until needed. This means that opening a file is very fast, regardless of file size and compressed format.
Third, cut and paste, paste and merge images
The Image class contains methods that allow you to manipulate areas in the image.
For example, to copy a subrectangular image from an image, use the crop () method.
1. Copy a subrectangle from an image
Example: capture a rectangular ima
Box = (100,100,400400) region = im.crop (box)
Define the box tuple, which means that the image is based on the coordinates of the upper left corner (0B0), and the box coordinates are (left, top, right, bottom). Note that the coordinates are based on pixels. 300 * 300 pixels in the example.
two。 Process the subrectangle and paste it back
Example: paste a sub-rectangular image on the original image
Region = region.transpose (Image.ROTATE_180) # reverse 180 degrees box = (400,400,700,700) # paste position, pixels must match, 300 * 300im.paste (region, box)
Note: when pasting (paste) the subimage (region) back to the original image, the pixels of the pasted position box must match the width and height. However, the mode of the original image and the sub-image does not need to be matched, and the Pillow will deal with it automatically.
Example: scrolling ima
From PIL import Imagedef roll (image, delta): "" xsize, ysize = image.size delta = delta% xsize if delta = = 0: return image part1 = image.crop ((0,0, delta, ysize)) part2 = image.crop ((delta, 0, xsize, ysize)) image.paste (part1, (xsize-delta, 0, xsize, ysize) image.paste (part2, (0,0, xsize-delta) Ysize)) return imageif _ _ name__ = ='_ _ main__': image_path = 'test.jpg' im = Image.open (image_path) roll (im, 300). Show () # scrolls 300 pixels to the side. Separate and merge channels
Pillow allows each channel of the image to be processed. For example, the RGB image has R, G and B channels. The split method separates the image channel and returns the image itself if the image is a single channel. The merge merge function takes the mode and channel tuples of the image as parameters to merge them into a new image.
Example: swap three bands of a RGB image
R, g, b = im.split () im = Image.merge ("RGB", (b, g, r))
Note: if you want to deal with monochrome, you can convert the picture to 'RGB'' first.
four。 Geometric transformation
PIL.Image.Image includes methods to resize the image resize () and rotate rotate (). The former uses tuples to give a new size, while the latter uses a counterclockwise angle.
Example: resize and rotate 45 degrees counterclockwise
Out = im.resize (128,128) out = out.rotate (45)
To rotate the image in 90 degrees, you can use the rotate () or transpose () methods. The latter can also be used to flip an image around its horizontal or vertical axis.
Example:
Out = im.transpose (Image.FLIP_LEFT_RIGHT) # flip out = im.transpose (Image.FLIP_TOP_BOTTOM) # flip up and down vertically out = im.transpose (Image.ROTATE_90) # counterclockwise 90 degrees out = im.transpose (Image.ROTATE_180) # counterclockwise 180 degrees out = im.transpose (Image.ROTATE_270) # counterclockwise 270 degrees
The rotate () and transpose () methods are the same, there is no difference between them, and the transpose () method is more general.
five。 Color transformation
Example: converting between mode
From PIL import Imageim = Image.open ("hopper.ppm"). Convert ("L") # convert to grayscale image
Note: it supports the conversion of each mode to "L" or "RGB". To convert between other modes, you must first convert the mode (usually a "RGB" image).
six。 Image enhancement 1. Filters filter
The ImageFilter module has a number of predefined enhancement filters that are applied through the filter () method.
Example: using filter ()
From PIL import ImageFilterout = im.filter (ImageFilter.DETAIL) 2. Pixel processing
The point () method can be used to convert the pixel values of an image, such as contrast, and in most cases, you can pass the function object as a parameter lattice this method, which processes each pixel based on the function return value.
Example: 1.2 times larger per pixel
Out = im.point (lambda I: I * 1.2)
The above method can not only process the image with a simple expression, but also process the local area of the image by combining point () and paste ().
3. Handle separate channels # separate channels source = im.split () R, G, B = 0,1, select areas less than 100red mask = source[ R] .point (lambda I: I < 100R255) # process green out = source[ G] .point (lambda I: I * 0.7) # paste processed channels, red channels are limited to
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.