Python uses pillow (PIL) as an example of image manipulation

Source: Internet
Author: User
Tags getcolor image processing library jupyter notebook

Color and RGBA values

The computer typically represents an image as an RGB value, or an alpha value (permeability, transparency), called an RGBA value. In pillow, the value of RGBA is expressed as a tuple of 4 integers, namely R, G, B, A. The range of integers is 0~255. RGB full 0 can represent black, all 255 for black. It can be guessed (255, 0, 0, 255) to represent red, because the R component is the largest, and the G and B components are 0, so it is red. However, when the alpha value is 0 o'clock, no matter what color, the color is not visible and can be understood as transparent.

From PIL import imagecolorprint (Imagecolor.getcolor (' Red ', ' RGBA ')) # You can also view print only in RBG (Imagecolor.getcolor (' black ' , ' RGB '))
(255, 0, 0, 255) (0, 0, 0)

The coordinate representation of the image

The upper- left corner of the image is the origin of the coordinates (0, 0), which is not the same as in normal mathematics. Such a defined coordinate system means that the x axis grows from left to right, while the Y axis grows from top to bottom.

How do you use the coordinate system defined above to represent a rectangular area in pillow? Many functions or methods require the supply of a rectangular tuple parameter. The tuple parameter contains four values that represent the distance from the x-axis or y-axis of the rectangle's four edges. The order is (左,顶,右,底) . Right and bottom coordinates are slightly special, and are indicated until but not included. Can be understood as [左, 右) and [顶, 底) so left closed right open interval. For example (3, 2, 8, 9) represents the horizontal axis range [3, 7]; the rectangular area of the ordinate range [2, 8].

Manipulating images with Pillow

Learn some basic knowledge, you can get started. Starting with reading the image, many image processing libraries (such as OPENCV) imread() read the picture. Methods used in Pillow open .

From PIL Import Imageim_path = R ' F:\Jupyter notebook\csv_time_datetime_pil\rabbit.jpg ' im = Image.open (im_path) width, Height = im.size# width high print (im.size, width, height) # format, and detailed description of the format print (Im.format, im.format_description) im.save (R ' \ c \ Users\administrator\desktop\rabbit_copy.jpg ') im.show ()
(1920x1080, 1920x1080) 1080JPEG JPEG (ISO 10918)

im.sizeReturns a tuple that is width and height, respectively. show()method invokes the system default image viewing software, which is opened and displayed. im.formatto view the format of the image. save()can save the processed picture, if untreated, the saved image occupies a space (number of bytes) is generally not the same as the original image, may have been compressed.

New Image

Pillow can also create a new blank image, the first parameter is mode, the color space pattern, the second parameter specifies the resolution of the image (width x height), and the third parameter is the color.

    • You can fill in the names of common colors directly. such as ' Red '

    • You can also fill in a hexadecimal representation of a color, such as #FF0000 red.

    • You can also pass in tuples, such as (255, 0, 0, 255) or (255, 0, 0) to indicate red.

# usually use RGB mode to be able to newim= image.new (' RGB ', (+), ' Red ') Newim.save (R ' C:\Users\Administrator\Desktop\1.png ') # You can also use the RGBA mode, there are other patterns to check the document bar Blcakim = image.new (' RGB ', (), ' Red ') Blcakim.save (R ' C:\Users\Administrator\Desktop\2. PNG ') # hex Color Blcakim = image.new (' RGBA ', (Max, Max), ' #FF0000 ') blcakim.save (R ' C:\Users\Administrator\Desktop\3.png ') # an RGBA value or RGB value in the form of an incoming tuple # in RGB mode, the fourth parameter fails, the default 255, in Rgba mode, can also only pass in the first three values, a value default 255blcakIm = Image.new (' RGB ', (200, 100), (255, 255 , 0, +)) Blcakim.save (R ' C:\Users\Administrator\Desktop\4.png ')


Cropping an image

ImageThere is a crop() way to receive a rectangular region tuple (mentioned above). Returns a new image object that is cropped and has no effect on the original.

im = Image.open (im_path) Cropedim = Im.crop ((------------) Cropedim.save (R ' C:\Users\Administrator\Desktop\ Cropped.png ')

Look at the original picture and the cropped image.

Copy and paste an image to another image

Imagecopyfunction, such as its name, produces a copy of the original image, and any operation on that copy will not affect the original image. paste()method is used to paste (overwrite) an image on top of another image. Who calls it, he modifies it directly on the image object.

im = Image.open (im_path) Cropedim = Im.crop ((0, 0, max)) Im.paste (Cropedim, ()) im.show () Im.save (R ' C:\Users \administrator\desktop\paste.png ')

im.show()Show image Discovery then IM (that is, the original) has been changed.

This will also use the original information, because the information is changed is very troublesome. So it is best to use a copy of paste before the copy copy() operation, which does not affect the original information. Although the original information in the program has changed, but because the file is saved with the other file name, the equivalent of the change does not take effect, so when viewing the original image has not changed.

im = Image.open (im_path) Cropedim = Im.crop ((0 (), Max, max) Copyim = Im.copy () copyim.paste (Cropedim, (0,)) im.show () Copyim.save (R ' C:\Users\Administrator\Desktop\paste.png ')

This time again look at the original image, has not changed. This ensures that when you use IM again, the information inside is still authentic. Let's look at an interesting example.

im = Image.open (im_path) Cropedim = Im.crop ((----) crop_width, crop_height = cropedim.sizewidth, height = i M.sizecopyim = Im.copy () for left in range (0, Width, crop_width): For top in range (0, height, crop_height):        copyim.paste (Cropedim, (left, top)) Copyim.save (R ' C:\Users\Administrator\Desktop\dupli-rabbit.png ')

With the cropped image width and height as an interval, the loop is pasted in the copy, which is a bit like taking a photo.

Resize an image

resizemethod returns a new image object of the specified width, accepting a tuple with a wide height as a parameter. the width of the high is worth an integer.

im = Image.open (im_path) width, height = Im.sizeresizedim = im.resize (width, height+ (1920-1080))) Resizedim.save (R ' \ c \ Users\administrator\desktop\resize.png ')

Rabbit thin, you can see resize is not proportional scaling.

Rotate and flip an image

rotate()Returns the new Image object after rotation, keeping the original images intact. Rotate counterclockwise.

im = Image.open (im_path) im.rotate (*). Save (R ' C:\Users\Administrator\Desktop\rotate90.png ') im.rotate (+). Save ( R ' C:\Users\Administrator\Desktop\rotate270.png ') im.rotate. Save (R ' C:\Users\Administrator\Desktop\ Rotate180.png ') im.rotate ((). Save (R ' C:\Users\Administrator\Desktop\rotate20.png ') im.rotate (expand=true). Save (R ' C:\Users\Administrator\Desktop\rotate20_expand.png ')

From top to bottom, respectively, is rotated 90°,180°, 270°, ordinary 20°, plus the parameter expand=True rotation of 20°. The expand enlarges the image size (to 2174x1672) so that the corner image is not cropped (Four corners just above the edge of the image). Then look at the rotation of 90°, 270° when the image is cropped, but the following view of the image of the width of the high, and it is the same as the original, do not understand.

Im90 = Image.open (R ' C:\Users\Administrator\Desktop\rotate90.png ') im270 = Image.open (R ' C:\Users\Administrator\ Desktop\rotate270.png ') # Width and height information does not change print (Im90.size, im270.size)
(1920, 1080) (1920, 1080)

Mirror flip of the image. transpose()functions can be implemented, must pass in Image.FLIP_LEFT_RIGHT or Image.FLIP_TOP_BOTTOM , the first one is a horizontal flip, the second is a vertical flip.

im = Image.open (im_path) im.transpose (image.flip_left_right). Save (R ' C:\Users\Administrator\Desktop\transepose_ Lr.png ') im.transpose (Image.flip_top_bottom). Save (R ' C:\Users\Administrator\Desktop\transepose_tb.png ')

Horizontal reversal can not be seen, the original image is horizontal symmetry ...

The vertical flip is obvious ...

Image filtering

Pillow the use of imagefilter can be simple image blur, edge enhancement, sharpness, smoothing and other common operations.

From PIL import Image, Imagefilterim = Image.open (im_path) # Gaussian Blur Im.filter (Imagefilter.gaussianblur). Save (R ' C:\Users\ Administrator\desktop\gaussianblur.jpg ') # normal blur Im.filter (Imagefilter.blur). Save (R ' C:\Users\Administrator\Desktop \blur.jpg ') # Edge Enhancement Im.filter (imagefilter.edge_enhance). Save (R ' C:\Users\Administrator\Desktop\EDGE_ENHANCE.jpg ') # Find Edge Im.filter (imagefilter.find_edges). Save (R ' C:\Users\Administrator\Desktop\FIND_EDGES.jpg ') # embossed Im.filter ( Imagefilter.emboss). Save (R ' C:\Users\Administrator\Desktop\EMBOSS.jpg ') # contour Im.filter (imagefilter.contour). Save ( R ' C:\Users\Administrator\Desktop\CONTOUR.jpg ') # Sharpening of Im.filter (Imagefilter.sharpen). Save (R ' C:\Users\Administrator\ Desktop\sharpen.jpg ') # smooth Im.filter (Imagefilter.smooth). Save (R ' C:\Users\Administrator\Desktop\SMOOTH.jpg ') # Details Im.filter (imagefilter.detail). Save (R ' C:\Users\Administrator\Desktop\DETAIL.jpg ')

In addition, if you want to draw the pattern, text, you can use Imagedraw. Pillow also has other powerful features that are not listed here.

In fact, pillow is just a basic image processing library. If you don't go into image processing, it's enough. Professionals who use OPENCV are better off choosing them. Use import cv2 in Python to start using it!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.