Python environment Pillow (PIL) parsing the image processing tools

This article describes the Python environment Pillow (PIL) image processing using the analytical tools, sample code by text describes in great detail, has a certain reference value of learning for all of us to learn or work, a friend in need can refer to the
Introduction

As the author of a recent research project related to the processed image, the need for transformation and processing of the image by image processing tools, and then generate the appropriate training image data. This series of articles that is mainly used tools and libraries recorded when the author of image processing in different environments. In Python environment, the author of image processing using the main libraries Pillow, comprising a main operation of the image reading, storage and transformation. In practice, Pillow provided Image module is adapted to transform the entire image processing operations.

NOTE: The following description includes only a basic module corresponding to the usage and function, and therefore some parameters and options are omitted in the introduction, usage and more complete description refer Pillow official documents.

installation

Pillow user can be directly installed through pip, additional installation can be found here.

pip install Pillow #安装 pillow

use

In the course of daily use, the most used is provided Pillow Image module is provided that includes an image storage, conversion, and a series of related processing. Pillow Image object used to represent the image based on the attribute information of the object and defining image and its operation may be performed for the subsequent operation of the image may be introduces i.e. performed by Image object. As used Python, the user first needs to import from the PIL module corresponding to the Image.

from PIL import Image #通过 Image 进行图像处理相关的操作

Image scanning and storage

Image read image provided by the open method, which is specified file name as an argument and returns a value corresponding to the Image object image, subsequent to the steps for the image corresponding Image object

im = Image.open( "test.png" )  # open 方法以图像名(或图像对象)为参数,返回一个 Image 对象

By storing the save method Image object image of an object, using parameter storage destination file name, the file may be stored in the format specified by the format parameter.

im.save( "test.png" )          # im 为 Image 对象,其被保存至 test.png,不指定 format 参数时,该方法通过文件后缀推测文件类型
im.save( "test.jpg" , format="JPEG")  # 以 JPEG 格式保存 Image 对象 im 至文件 test.jpg 中

The basic properties

Image object corresponding to the image have basic properties. Users can get the most basic image information through these properties, complete property information Image objects can be viewed here.

im.filename    # Image 对象 im 对应的文件/路径名
im.mode      # Image 对象图像数据的解释方式,如灰度图为 “L”,彩色图为 “RGB”等
im.size      # 返回图像的尺寸信息,为( width , height ) 格式的元祖

Image type conversion

Different image data having different image formats, and thus have different ways of organizing data. For RGB images, the image has R, G, B three channels, consists of three 8 bit pixel data corresponding to a three-channel data composed of; for black and white images, each pixel is represented by an 8 bit byte and so on . When an image is opened, will automatically parse method Open image format, the user can be obtained by state of the image object Image mode attribute.

Image objects can be carried out by methods convert the type of conversion between images, using a conversion target parameter string type, the conversion Image object returns, common types include RGB (true color), L (black and white), the YCbCr (video image), HSV (hue saturation brightness color space).

data = im.convert( "L" )    #获得 RGB 图像 im 的灰度图

Conversion and numpy array

In the procedure, typically using an image corresponding Image object operation image related generally converted for the calculation processing of the image data itself is Image object after numpy data processing numpy data after completion reconverted to Image object save.

a. converting Image object array numpy

Use numpy.asarray method (not unique, see Array creation routines) Image data converted to object numpy array, further processing can be calculated. After converting the data type array numpy Image data objects in accordance with the data type inference obtained itself, but also specify the data type using the conversion parameter numpy.asarray dtype during use.

 im = Image.open( "test.png" )         #打开图像 test.png ,并获得其对应的 Image 对象
data = numpy.asarray( im )           #将 Image 对象 im 的数据转换为 numpy 数组的形式,data 即为可供运算的 numpy 数组
data = numpy.asarray( im, dtype=np.uint8 )   #转换图像数据为 numpy 数组,并指定其类型为 np.uint8

b. to convert the numpy array to Image object

Numpy data for the image data of the form (or processed data obtained by other means), can be obtained by the conventional method Image.fromarray numpy image data into Image object.

im = Image.fromarray( data ) # data 为 numpy 数组,im 为转换获得的 Image 对象

Note that an error may occur raise TypeError ( "Can not handle this data type") when using Image.fromarray method, which is due to be numpy data type conversion may not be consistent with the type of data needed to Image object (usually 8 bit unsigned value), before the solution is to first convert the data to an array type conversion numpy np.uint8

 im = Image.fromarray( data.astype( np.uint8 ) )  #将 numpy 数组的数据类型转换为 np.uint8 后再转换为 Image 对象

Common Operations

Cropped image --crop

The method may be used to obtain crop designated portion of the image. Methods specify crop (left, top, right, bottom) ancestral cutting position to the image portion to be segmented is defined, it is understood that the definition of the coordinates of left and right corners of the rectangle obtained by cutting positions. PIL supported coordinate system, the coordinates (0, 0) is the upper left corner of the image, noted (0, 0) of the upper left corner of the first pixel is not a point, but a position before the pixel position, all subsequent the coordinates of the location are gaps between pixels, rather than to pixels. That is, the first pixel is (0, 0) (0, 1) and surrounded by two right and left coordinates.

part = im.crop( ( 0 , 0 , 100 , 100 ) ) #截取获得图像 im 左上角大小为 100 × 100 像素的矩形图像

Channel processing --split / getchannel

The method of split image data by channel separation, which returns the tuple value tuple comprises respective separate data channels, as described for the RGB image, the data which is divided into three channels R, G, B

R, G, B = im.split() # im 为真彩色 Image 对象,其被分为独立的 R、G、B 通道信息

Methods getchannel character of the name or index of the channel parameters of the image, the image comprising a return type L with a corresponding data channel (i.e. black and white).

R = im.getchannel( 0 )  # 获得 RGB 图像的第一个通道的数据,即 R 通道信息
R = im.getchannel( "R" ) #同上

Zoom image --resize

resize method to scale the size of the target image tuples (Width, Heigth) as a parameter, by specifying sampling method to scale the image in the specified image size. See all the documentation which supports sampling methods sampling methods include PIL.Image.NEAREST, PIL.Image.BILINEAR, PIL.Image.BICUBIC etc., resize support. Note that the above method of sampling the full name PIL.Image.xxxx, but actually has been used previously since from PIL import Image Image introduced into the module name, and therefore can be used directly in the form of subsequent calls to the methods of Image.xxxx, on the contrary, in when the need to use the full name of the module name is not introduced to the method described above, the same below.

data = im.resize( ( 100, 100 ) )             #将 im 对应的 Image 对象缩放为 100×100 的大小,默认采用 PIL.Image.NEAREST 方法
data = im.resize( ( 100, 100 ), Image.BICUBIC )     #使用 PIL.Image.BICUBIC 方法进行采样

Flip image --rotate / transpose

Rotating the image, rotate method rotate by the rotation angle method as a parameter, the number of degrees corresponding to the rotation center of the image clockwise, and returns the corresponding Image object. Note that, when rotated by the rotate method, the resultant image after image rotates within the size range of the source image portion is taken, the other part is filled. The image size is width × height 200 * 100, after a 90 degree rotation, the size is still 200 * 100, the image content theory rotated as part of the original image and the overlap area 200 * 100 100 * 200, the remaining partially filled.

The new method may rotate the image to a specified parameter expand, a new image is generated at this time contains the image content after complete rotation of the minimum rectangle size (to fill the space), in the above embodiment, the image rotated through 90 degrees, obtained It is the size of 100 * 200. See more of the description Image.rotate.

data = im.rotate( 90 ) #将图像顺时针旋转 90 度
data = im.rotate( 90 , expand=1 ) #将图像顺时针旋转 90 度,同时保留图像的完整内容

In the training data generating some images, the image 90 degrees of rotation, up and down or left and right are inverted more common operations. In this case the method can transpose, transpose way to flip parameter back through the image inversion, it supports the parameters are as follows.

PIL.Image.FLIP_LEFT_RIGHT  #左右翻转图像
  PIL.Image.FLIP_TOP_BOTTOM  #上下翻转图像
  PIL.Image.ROTATE_90
  PIL.Image.ROTATE_180
  PIL.Image.ROTATE_270     #顺时针旋转对应度数
  PIL.Image.TRANSPOSE     #类似于左右翻转后再逆时针旋转图像 90 度
  PIL.Image.TRANSVERSE     #类似与左右翻转后再顺时针旋转图像 90 度

It may be used as the above-described image transformation parameters, a complete image conversion method returns the transpose (because it is a multiple of 90 degrees, there is no blank area).

data = im.transpose( Image.FLIP_LEFT_RIGHT ) #获得 im 图像经过左右旋转后的数据

We recommend learning Python buckle qun: 774711191, look at how seniors are learning! From basic web development python script to, reptiles, django, data mining, etc. [PDF, actual source code], zero-based projects to combat data are finishing. Given to every little python partner! Every day, Daniel explain the timing Python technology, to share some of the ways to learn and need to pay attention to small details, click to join our gathering python learner

Published 43 original articles · won praise 30 · views 60000 +

Guess you like

Origin blog.csdn.net/haoxun09/article/details/104806752