Create a text image using Python PIL

Source: Internet
Author: User

The PIL library contains many modules that can be used properly for image processing.

The following is the class and test code I used to generate letters or strings for testing images.

Main modules used:

PIL. Image, PIL. ImageDraw, PIL. ImageFont

PIL. Image is used to generate an empty Image. ImageDraw is used to draw and write characters on the empty Image. ImageFont is used to create the font to be used.

#-*-Coding: gb2312-*-from PIL import Image, ImageDraw, ImageFont, ImageOpsimport numpy as npimport randomclass LetterImage (): def _ init _ (self, fontFile = '', imgSize = (255,255,255), imgMode = 'rgb ', bg_color = (, 0), fg_color = (), fontsize = 20): self. imgSize = imgSize self. imgMode = imgMode self. fontsize = fontsize self. bg_color = bg_color self. fg_color = fg_color # self. font = ImageFont. load ('license plate font. ttf') if ''= fontFile: self. font = ImageFont. truetype ('din1451. ttf', fontsize) else: self. font = ImageFont. truetype (fontFile, fontsize) def GenLetterImage (self, letters): '''generate the Image of letters ''' self. letters = letters (self. letterWidth, self. letterHeight) = self. font. getsize (letters) if self. imgSize = (0, 0): self. imgSize = (self. letterWidth + 2, self. letterHeight + 2) self. imgWidth, self. imgHeight = self. imgSize self. img = Image. new (self. imgMode, self. imgSize, self. bg_color) self. drawBrush = ImageDraw. draw (self. img) textY0 = (self. imgHeight-self.letterHeight + 1)/2 textY0 = int (textY0) textX0 = int (self. imgWidth-self.letterWidth + 1)/2) print 'text location: ', (textX0, textY0) print 'text size (width, height):', self. letterWidth, self. letterHeight print 'img size (width, height): ', self. imgSize # if textX0 <0 or textY0 <0: # raise Exception ('size error text location x0: % d, y0: % d' % (textX0, textY0) self. drawBrush. text (textX0, textY0), self. letters, fill = self. fg_color, font = self. font) def SaveImg (self, saveName = ''): if'' = saveName. strip (): saveName = str(self.letters.encode('gb2312'{}'.png 'fileName, file_format = saveName. split ('. ') fileName + =' _ '+ str (self. fontsize) + '. '+ file_format print fileName, file_format self. img. save (fileName, file_format) def Show (self): self. img. show () def clearpictures (): import OS png = OS. listdir (OS. curdir) for I in png: if OS. path. splitext (I) [1] = ". png ": OS. remove (I) if _ name __= = '_ main _': letterList = [] letterList. append (LetterImage (bg_color = (0,0, 255), fontsize = 10) letterList. append (LetterImage (fontFile = '', bg_color = (255, 400), fontsize =) letter = [u'u ', u'v'] num_letter = 2 svd_u = [] svd_s = [] svd_v = [] import cv2 mergeImg = np. zeros (470,444) npareiImg = [] for I in range (num_letter): letterList [I]. genLetterImage (letter [I]) # letterList [I]. show () # letterList [I]. saveImg () grayImg = ImageOps. grayscale (letterList [I]. img) grayImg = grayImg. resize (222,470), resample = Image. BICUBIC) npareiImg. append (np. asarray (grayImg) cv2.namedWindow ('% s' % I) cv2.imshow (' % s' % I, npareiImg [I]) mergeImg [0: 470, I * 222 :( I + 1) * 222] = npareiImg [I] u, s, v = np. linalg. svd (npareiImg [I]) print 'U and img \'s shape', u. shape, npareiImg [I]. shape svd_u.append (u) svd_v.append (v) svd_s.append (s) # mergeImgNp = Image. fromarray (mergeImg) #, mode) # mergeImgNp. show () uDifNorm = np. linalg. norm (svd_u [0]-svd_u [1]) print uDifNorm vDifNorm = np. linalg. norm (svd_v [0]-svd_v [1]) print vDifNorm sDifNorm = np. linalg. norm (svd_s [0]-svd_s [1]) print sDifNorm ou_norm = np. linalg. norm (np. asarray (npareiImg [0])-np. asarray (npareiImg [1]) print ou_norm f1_open('record.txt ', 'A') lines = [] lines. append ('Letters: % s, % s' % (letter [0], letter [1]) lines. append ('svd u diff norm: \ t % F' % uDifNorm) lines. append ('svd v diff norm: \ t % F' % vDifNorm) lines. append ('svd s diff norm: \ t % F' % sDifNorm) lines. append ('ou norm: \ t % F' % ou_norm) str_to_write = '\ n '. join (lines) + '\ n' print str_to_write f. write (str_to_write) f. close () cv2.waitKey ()

The above test is a bit of an experiment that performs SVD transformation on the image.

Display result (the image has been resize to a uniform size, and the image generated by the character image class in the code will be automatically set according to the font size)

#-*-Coding: gb2312-*-specify to use Chinese encoding. In this case, there will be no errors. But sometimes we may need to convert and encode some strings. In this case, we can use the encode and decode methods of character objects. Encode re-encodes the current character using the specified encoding scheme. Decode uses the specified encoding scheme for decoding. Both of them are code conversion, but they are often mistaken during use.In fact, encode uses the specified character encoding for unicode characters, while decode uses the specified encoding to decode the characters into unicode encoding.. When using encode, if it is not a unicode code, it will cause an error. When using decode, if you do not know the encoding scheme used, it will also cause an error.

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.