Python image processing Module Pillow Learning

Source: Internet
Author: User

69206210

Today took time to learn a bit before the pillow library, previously seen remember this library can be added to the picture text plus numbers, but also to convert the picture into a character painting, but has not been looking to learn this module, because the holiday does not have to train, so it was blind to engage in a bit

0, 工欲善其事, its prerequisite

There are several ways to install the Pillow Library
0. Install with PIP

$ pip install pillow
    • 1

1. Using Easy_install

$ easy_install pillow
    • 1

2. Installation via Pycharm

1. Learn and use the Pillow Library
 #导入模块 from PIL import Image #读取文件img = Image.open ( ' test.jpg ')  #保存文件  #img. Save (Filename,format) Img.save (Filename, "JPEG")  #获取图片大小 (width,height) = Img.size #获取图片的源格式img_format = img.format< Span class= "hljs-comment" > #获取图片模式, three modes: L (grayscale image), RGB (True Color) and CMYK (pre-press image) Img_mode = Img.mode  #图片模式的转换img = Img.convert ( "L") # Convert to Grayscale image  #获取每个坐标的像素点的RGB值r, g,b = Img.getpixel ((j,i)) # Reset Picture size img = img.resize (width,height)  #创建缩略图img. Thumbnail (size)  
2, the actual combat walkthrough will convert the picture into character painting, the effect is as follows:





In fact, it should be easy to think, if you want to achieve this effect, you should be able to get the RGB value of each point on the graph, and then according to the three kinds of values to determine what the character, in fact, according to the RGB to determine the value of the gray, so you can convert the image to grayscale image, to directly get the grayscale of or convert RGB values to grayscale using grayscale conversion formulas

#coding: Utf-8From PILImport Image#要索引的字符列表ascii_char = List ("[Email protected]%8&wm#*oahkbdpqwmzo0qlcjuyxzcvunxrjft/\| () 1{}[]?-_+~<>i!li;:,\ "^". ") length = Len (Ascii_char) img = Image.open (' 03.jpg ')#读取图像文件 (width,height) = Img.sizeimg = Img.resize ((int (width*0.9), Int (height*0.5)))#对图像进行一定缩小print (Img.size)DefConvert(IMG): img = Img.convert ("L")# Convert to grayscale image txt =""For IIn range (img.size[1]):For JIn range (img.size[0]): Gray = Img.getpixel ((j, I))# Gets the grayscale unit for each coordinate pixel point =256.0/length txt + = Ascii_char[int (gray/unit)]#获取对应坐标的字符值 txt + =' \ n 'Return txtDefConvert1(IMG): txt =""for i in range (Img.size[1]): for J in range (Img.size[0]): R,g,b = Img.getpixel ((J, i))  #获取每个坐标像素点的rgb值 gray = Int (R * 0.299 + G * 
                                             
                                              0.587 + b * 
                                              0.114)  #通过灰度转换公式获取灰度 unit = ( Span class= "Hljs-number" >256.0+1)/length txt + ascii_char[int (gray/unit)] # gets the corresponding coordinates of the character value txt + =  \ n ' return txttxt = CONVERT ( IMG) F = open ( "03_convert.txt",  "W") f.write (TXT)  #存储到文件中f. Close ()         
                                             
Add text to the picture (welfare alert, there are benefits ahead!!!!) )
 #coding: Utf-8from PIL import Image,imagedraw,imagefont #http://font.chinaz.com/zhongwenziti.html font Download site img = Image.open ( ' pdd01.jpg ') draw = Imagedraw.draw (img) myfont = imagefont.truetype ( ' Hyliuziheij.ttf ', Size=80) FillColor =  ' Pink ' ( width, height) = Img.size #第一个参数是加入字体的坐标  #第二个参数是文字内容  #第三个参数是字体格式  #第四个参数是字体颜色draw. Text (40, 100), u ' Meng Meng ', Font=myfont,fill=fillcolor) Img.save ( ' modfiy_pdd01.jpg ',  ' jpeg ')   


Add a number to a picture

This people should have seen, is some of the head of the upper left corner of the small red circle plus white numbers, in fact, the method and the above the text of the same

To be reasonable, I might as well use PS to move coordinates to death.

#coding:utf-8from PIL import Image,ImageDraw,ImageFontimg = Image.open("03.jpg")draw = ImageDraw.Draw(img)myfont = ImageFont.truetype(u"时光体.ttf",50)(width,height) = img.sizedraw.ellipse((width-40,0,width,40),fill="red",outline="red") #在图上画一个圆draw.text((width-30,-8),‘1‘,font=myfont,fill=‘white‘)img.save(‘03_modify.jpg‘)
Generate 4-bit random verification code

#coding: Utf-8From PILImport Image,imagedraw,imagefont,imagefilterImport Random"" Create a four-digit code "" "#产生随机验证码内容DefRndtxt(): txt = [] Txt.append (Random.randint (97,123))#大写字母 Txt.append (Random.randint (65,90))#小写字母 Txt.append (Random.randint (48,57))#数字Return Chr (Txt[random.randint (0,2)])#随机颜色 (background)DefRndColor1():Return (Random.randint (64,255), Random.randint (64,255), Random.randint (64,255))#随机颜色 (font)DefRndColor2():Return (Random.randint (32,127), Random.randint (32,127), Random.randint (32,127))#240x60: width =60*4height =60img = Image.new (' RGB ', (width,height), (255,255,255)) Font = Imagefont.truetype (u ' time body. Ttf ', 36) draw = Imagedraw.draw (img) Span class= "hljs-comment" > #填充每个像素 for x in Range (width): for y in Range (height): Draw.point ((x, y), Fill=rndcolor1 ())  #输出文字 for txt in range (4): Draw.text ((60*txt+10, 10), Rndtxt (), Font=font,fill=rndcolor2 ())  #模糊化处理  #img = Img.filter (Imagefilter.blur) img.save ( "code.jpg")    

Python image processing Module Pillow Learning

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.