Python PIL library of image processing operations Explanation

1 Introduction

2. PIL What can be done?

    PIL can do a lot of image processing and related things:

  • Picture Archiving (Image Archives) . PIL is ideal for batch jobs picture archiving and image. You can use the PIL create thumbnails, convert image formats, image printing and so on.
  • The image shows (Image Display) . PIL newer version includes support for Tk PhotoImage, BitmapImage well as Windows DIB and other interfaces. PIL support many GUI framework interface, can be used for image display.
  • Image Processing (Image Processing) . PIL include basic image processing functions, including processing point, using a large number of convolution kernel (convolution kernels) as filter (filter), as well as color space conversion. PIL library size also supports conversion, image rotation, and any affine transformation of the image. PIL Some histogram method, allowing some statistical properties of your display image. This can be used for automatic image contrast enhancement, as well as statistical analysis of global and so on.

3. How to use PIL?

3.1 Image class

    PIL Image class is the core class, there are many ways you initialize it, such as loading an image from a file, other forms of image processing, or re-create an image and so on. The following is a PIL Image class commonly used methods:

Python PIL library of image processing operations Explanation

  • Open (filename, the MODE) (an image open). The following code demonstrates how to open an image from a file:

>>> from PIL import Image
>>> Image.open("niuniu.jpg","r")
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=450x600 at 0x7F715DC61320>
>>> im = Image.open("niuniu.jpg","r")
>>> print(im.size,im.format,im.mode)
(450, 600) JPEG RGB

 Python PIL library of image processing operations Explanation

Image.openReturns an Image object has size,format,modeattributes, wherein sizean image representing the width and height (in pixels); formatrepresents the image formats, including common JPEG, PNG and other formats; moderepresents mode image, there are defined pixel type image depth etc., are common RGB, HSV and so on. Generally 'L' (luminance) represented by gray scale image, 'RGB' represents a true color image, 'CMYK' represents a pre-compressed images. Once you get to open the Image object, you can use its many methods for image processing, and such use im.show()can show images obtained above.

  • Save (filename, the format) (save the image in a specified format)
>>> im.save("linuxidc.png",'png')

The above code is saved as image re png format.

  • thumbnail The (size, resample) (create thumbnails)
>>> im.thumbnail((50,50),resample=Image.BICUBIC)
>>> im.show()

The above code creates a thumbnail specified size (size), it is necessary to note that, thumbnail The operation method is in situ, the return value is None. The first parameter is the size specified by the thumbnail, a second sample, there is Image.BICUBIC, PIL.Image.LANCZOS, PIL.Image.BILINEAR, PIL.Image.NEARESTfour sampling. Default Image.BICUBIC.

  • Crop Allows you (Box) (cropping rectangle area)
>>> im = Image.open("niuniu.jpg","r")
>>> box = (100,100,200,200)
>>> region = im.crop(box)
>>> region.show()
im.crop()

Python PIL library of image processing operations Explanation

The above code cropped region on a rectangular box im image, and then displayed. box is a four digit tuple (upper_left_x, upper_left_y, lower_right_x, lower_right_y), respectively, the upper left corner of the cropping rectangle area x, y coordinates, the coordinates of the upper left corner of the lower right corner of the x, y coordinates, a predetermined image is (0,0), the width direction of the x-axis, y-axis is the height direction, each pixel represents a coordinate unit. crop () returns remains an Image object.

  • TRANSPOSE (Method) (Image rotation or flipping)
>>> im_rotate_180 = im.transpose(Image.ROTATE_180)
>>> im_rotate_180.show()

Python PIL library of image processing operations Explanation

The above code im counterclockwise rotation of 180 °, and then displayed, methodis the transpose parameter indicates what kind of flipping or rotating mode is selected, the value may be selected are:
    - Image.FLIP_LEFT_RIGHT, shows a left and right inverted images
    - Image.FLIP_TOP_BOTTOM , shows a vertically inverted image
    - Image.ROTATE_90, the image shows a counterclockwise rotation [deg.] 90
    - Image.ROTATE_180, the image shows a counterclockwise rotation [deg.] 180 [
    - Image.ROTATE_270, the image shows a counterclockwise rotation [deg.] 270
    - Image.TRANSPOSE, represents the transposed image (corresponding to clockwise rotation [deg.] 90)
    - Image.TRANSVERSE, shows a transposed image, and then horizontally flipped

  • paste (region, box, mask) (one image to another image paste)
>>> im.paste(region,(100,100),None)
>>> im.show()

The above code image region is adhered to the upper left corner (100, 100) position. Image region is pasted to the object, box to paste position, a tuple of two elements, the coordinates of the upper left corner area of ​​the paste, or may be a tuple of four elements, left and right corners indicates coordinate of. If yes, then four elements of a tuple, box of size and region of size must be consistent, otherwise it will be convert into a region and the same size.

  • Split () (color channel separation)
>>> r,g,b = im.split()
>>> r.show()
>>> g.show()
>>> b.show()

Python PIL library of image processing operations Explanation

split () method can separate the original image for each channel, for example, an RGB image may be R, G, B three color channels separated.

  • Merge (MODE, channels) (Merge color channels)
>>> im_merge = Image.merge("RGB",[b,r,g])
>>> im_merge.show()

Python PIL library of image processing operations Explanation

Method split and merge methods are relative, which sequence of a plurality of single channels merge together to form a multi-channel image, mode is a mode after combined image, such as "RGB", channels a single channel is composed of a plurality of sequences.

  • resize(size,resample,box)

>>> im_resize = im.resize((200,200))
>>> im_resize
<PIL.Image.Image image mode=RGB size=200x200 at 0x7F715B19CCF8>
>>> im_resize.show()
>>> im_resize_box = im.resize((100,100),box = (0,0,50,50))
>>> im_resize_box.show()

Python PIL library of image processing operations Explanation

size after resize ways to convert the original image size, size is a conversion, resample re-sampling method is used, there is still Image.BICUBIC, PIL.Image.LANCZOS, PIL.Image.BILINEAR, PIL.Image.NEARESTfour sampling methods, default PIL.Image.NEAREST, box is a designated area to resize the image, is a region (above meaning and the same box) with a specified set of four yuan.

  • convert(mode,matrix,dither,palette,colors)(mode转换)
>>> im_L = im.convert("L")
>>> im_L.show()
>>> im_rgb = im_L.convert("RGB")
>>> im_rgb.show()
>>> im_L.mode
'L'
>>> im_rgb.mode
'RGB'

Python PIL library of image processing operations Explanation

The method can convert an image mode change, generally in the 'RGB' (true color image), 'L' (grayscale), the conversion between 'CMYK' (FIG compression). The above code is the first image is converted to grayscale and then converted to grayscale from true color image. It is noteworthy that, grayscale conversion from true color pictures, although in theory does the conversion was successful, but in fact it is difficult to return to the original true color mode (not unique).

  • filter (filter) (applying a filter)
>>> im = Image.open("niuniu.jpg","r")
>>> from PIL import ImageFilter
>>> im_blur = im.filter(ImageFilter.BLUR)
>>> im_blur.show()
>>> im_find_edges = im.filter(ImageFilter.FIND_EDGES)
>>> im_find_edges.show()
>>> im_find_edges.save("linuxidc.jpg")
>>> im_blur.save("linuxmi.jpg")

Some filter method may be applied to the original image filter operation, such as the fuzzy operation, to find the edge, corner operation. filter is a filter function, in PIL.ImageFilterthe definition of a number of built-in functions of the filter function, such as BLUR(fuzzy operation), GaussianBlur(Gaussian blur), MedianFilter(median filter), FIND_EDGES(lookup side) and the like. Figure 1 below:

Python PIL library of image processing operations Explanation

figure 1

  • Point (LUT, MODE) (operation image pixels)
>>> im_point = im.point(lambda x:x*1.5)
>>> im_point.show()
>>> im_point.save("linuxidc.jpg")

Method point operation may be made to a single pixel of an image, the above method of passing point code an anonymous function, represents the size of each pixel of the image are multiplied by 1.5, mode-mode image is returned, the default is the original mode image is the same. FIG 2 is a comparison between original dog.jpg im_point.jpg and after the operation point.

Python PIL library of image processing operations Explanation

The following is a combination of a pointfunction, splitthe function, pastethe function and the mergesmall example function.

>>> source = im.split()
>>> R,G,B = 0,1,2
>>> mask = source[R].point(lambda x: x<100 and 255) 
>>> # x<100,return 255,otherwise return 0
>>> out_G = source[G].point(lambda x:x*0.7)
>>> # 将out_G粘贴回来,但是只保留'R'通道像素值<100的部分
>>> source[G].paste(out_G,None,mask)
>>> # 合并成新的图像
>>> im_new = Image.merge(im.mode,source)
>>> im_new.show()
>>> im.show()
  • ImageEnhance () (image enhancement)
>>> from PIL import ImageEnhance
>>> brightness = ImageEnhanBce.Brightness(im)
>>> im_brightness = brightness.enhance(1.5)
>>> im_brightness.show()
>>> im_contrast = ImageEnhance.Contrast(im)
>>> im_contrast.enhance(1.5)
<PIL.Image.Image image mode=RGB size=296x299 at 0x7F62AE271AC8>
>>> im_contrast.enhance(1.5).show()

ImageEnhance is a subclass of the PIL, mainly for image enhancement, such as to increase the brightness (the Brightness), to increase the contrast (Contrast) and the like. The above code will increase by 50% brightness of the original image, the contrast also increased by 50%.

  • ImageSequence () (process a sequence of images)
    The following code can traverse all frames gif image and saved as an image respectively
>>> from PIL import ImageSequence
>>> from PIL import Image 
>>> gif = Image.open("pipixia.gif")
>>> for i,frame in enumerate(ImageSequence.Iterator(gif),1):
...     if frame.mode == 'JPEG':
...         frame.save("%d.jpg" %i)
...     else:
...         frame.save("%d.png" % i)

In addition to the above embodiment using the iterator, one can read a gif, such as the following code:

>>> index = 0
>>> while 1:
...     try:
...         gif.seek(index)
...         gif.save("%d.%s" %(index,'jpg' if gif.mode == 'JPEG' else 'png'))
...         index += 1
...     except EOFError:
...         print("Reach the end of gif sequence!")
...         break

After reading the above code to the last one gif, it will throw a EOFError, so we just catch the exception on it.

Guess you like

Origin www.linuxidc.com/Linux/2019-09/160566.htm