python: PIL library study notes

Overview of PIL library:

The PIL library can fulfill both image archiving and image processing functional requirements:
  image archiving: batch processing of images, generating image previews, image format conversion, etc .;
  image processing: basic image processing, pixel processing, color processing, etc.  

PIL library Image class:

 

from PIL Import Image 
m = Image.open ( " D: \\ picture.jpg " )    # read photo files

 

Generate thumbnails:

im.thumbnail ((128, 128))     # (128, 128) is the size of the thumbnail. 
im.save ( " birdnestTN " , " JPEG " ) 
im.show ()    # display thumbnails (thumbnails can not simply double-click to open, and can be used PIL.image the open reading, and then use the show () method displays)

Rotate and zoom:

im.rotate (45)     # Image.rotate (angle) rotate the image by angle 
im.resize (128)    # Image.resize (size) adjust the image by size 
im.show ()

 

Image color exchange

R & lt, G, B = im.split ()    # extract each color channel of the RGB image 
OM = Image.merge ( " RGB " , (B, G, R & lt))    # The channels are each independently a new image resynthesis 
om.save ( ' pictureBGR.jpg ' )

Image filtering and enhancement

 

Image outline acquisition:

from PIL import Image
from PIL import ImageFilter
im = Image.open("picture.jpg")
om = im.filter(ImageFilter.CONTOUR)
om.save('pictureContour.jpg')

                                       

Adjust color, brightness, contrast, sharpen

 

 

 Embossed

from PIL import Image
from PIL import ImageFilter
im = Image.open("picture.jpg")
om = im.filter(ImageFilter.EMBOSS)
om.save('picture1.jpg')

Extract every frame of animation

from the PIL Import Image 
IM = Image.open ( ' movable FIG .gif ' )       # reads a GIF file 
the try : 
    im.save ( ' picframe {:} .png 02d ' .format (im.tell ()))
     the while True : 
        im.seek (im.tell () +1 ) 
        im.save ( ' picframe {: 02d} .png ' .format (im.tell ()))
 except :
     print ( " end of processing " )

 Chinese character painting

from PIL import Image 
ascii_char   = list ( ' China is really a great country ' )
 def get_char (r, b, g, alpha = 256 ):
     if alpha == 0:
         return  '  ' 
    gray = int (0.2126 * r + 0.7152 * g + 0.0722 * b) 
    unit = 256 / len (ascii_char)
     return ascii_char [int (gray // unit)]
 def main (): 
    im = Image.open ( ' pic.PNG ' ) 
    WIDTH, HEIGHT = 100, 60 
    im = im.resize((WIDTH, HEIGHT))
    txt = ""
    for i in range(HEIGHT):
        for j in range(WIDTH):
            txt += get_char(*im.getpixel((j, i)))
        txt += '\n'
    fo = open("pic_char.txt","w")
    fo.write(txt)
    fo.close()
main()

 

Guess you like

Origin www.cnblogs.com/linjiaxin59/p/12695287.html