PIL库中包含了很多模块,恰当地利用这些模块可以做许多图像处理方面的工作。

下面是我用来生成字母或字符串测试图片而写的类及测试代码。

主要用到的模块:

PIL.Image,PIL.ImageDraw,PIL.ImageFont

PIL.Image用来生成一个空的图片,ImageDraw用来在空图片上画图及写字符,ImageFont则是创建需要使用到的字体

主要用到的代码:

#创建一个空的图片
self.img = Image.new(self.imgMode, self.imgSize, self.bg_color) self.drawBrush = ImageDraw.Draw(self.img)#创建画刷,用来写文字到图片img上 #创建字体,fontFile为字体文件,若非系统字体需加详细路径
self.font = ImageFont.truetype(fontFile,fontsize)
#使用特定字体写字,(textX0,textY0)为文字开始的左上角起始位置 self.drawBrush.text((textX0,textY0), self.letters, fill=self.fg_color,font=self.font)

 

详细代码:

#-*- coding:gb2312 -*-
from PIL import Image,ImageDraw,ImageFont,ImageOps
import numpy as np
import random class LetterImage(): def __init__(self,fontFile='',imgSize=(0,0),imgMode='RGB',bg_color=(0,0,0),fg_color=(255,255,255),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('车牌字体.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=(0,0,255),fontsize=400))
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
f=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()

上面的测试后部分是对图像做SVD变换的一点实验。

显示的结果(图像已经被resize到统一大小,代码中的字符图像类生成的图像其实会根据字体大小自动设定)

当然,生成这种测试图像也不一定就非得用PIL或者python,matlab中应该也可以,其实也就是先生成一个空的图像矩阵,然后调用写字符的函数在这个空图像上以特定的字体写上字符串罢了。

使用汉字字体时要注意的问题:

一般的做法是在文件开头的位置加上#-*- coding:gb2312 -*- 指定使用中文编码。这样一般不会有错。但有时可能我们需要对部分字符串转换编码,这时我们可利用字符对象的encode、decode方法。encode是对当前字符使用指定的编码方案重新编码。decode是使用指定的编码方案进行解码。两者都是码制的转换,但使用时往往容易弄错。encode其实是对本身为unicode的字符使用指定的编码方案进行编码,而decode则是使用指定编码将字符解码为unicode编码。所以在使用encode时,如果本身不是unicode码就会出错,在使用decode时,如果不知道本身所使用的编码方案也会出错.

Python PIL创建文字图片的更多相关文章

  1. 基于Python PIL实现简单图片格式转化器

    基于Python PIL实现简单图片格式转化器 目录 基于Python PIL实现简单图片格式转化器 1.简介 2.前期资料准备 2.1.1如何实现图片格式转换? 2.1.2如何保存需要大小的图片? ...

  2. Python,PIL压缩裁剪图片

    自己写了用来压缩 DC 照片的,批量处理整目录文件,非常方便.需要安装 PIL #!/usr/bin/env python import Image import os import os.path ...

  3. Python PIL模块笔记

    利用python pil 实现给图片上添加文字 图片中添加文字#-*- coding: utf-8 -*- from PIL import Image,ImageDraw,ImageFont ttfo ...

  4. java生成竖排文字图片

    package com.kadang.designer.web.action;import java.awt.Color;import java.awt.Font;import java.awt.Fo ...

  5. 基于PIL模块创建验证码图片

    def get_valid_img(request): # 方式2:基于PIL模块创建验证码图片 from PIL import Image, ImageDraw, ImageFont from io ...

  6. Python批量创建word文档(2)- 加图片和表格

    Python创建word文档,任务要求:小杨在一家公司上班,每天都需要给不同的客户发送word文档,以告知客户每日黄金价格.要求在文档开始处给出banner条,价格日期等用表格表示.最后贴上自己的联系 ...

  7. python PIL 图像处理操作

    python PIL 图像处理 # 导入Image库 import Image # 读取图片 im = Image.open("1234.jpg") # 显示图片 im.show( ...

  8. Python简单的制作图片验证码

    -人人可以学Python--这里示范的验证码都是简单的,你也可以把字符扭曲 人人可以学Python.png Python第三方库无比强大,PIL 是python的一个d第三方图片处理模块,我们也可以使 ...

  9. python PIL 图像处理

    python PIL 图像处理 This blog is from: https://www.jianshu.com/p/e8d058767dfa Image读出来的是PIL的类型,而skimage. ...

随机推荐

  1. CQRS学习——Cqrs补丁,async实验以及实现[其二]

    实验——async什么时候提高吞吐 async是一个语法糖,用来简化异步编程,主要是让异步编程在书写上接近于同步编程.总的来收,在await的时候,相当于附加上了一个.ContinueWith(). ...

  2. 基于局部敏感哈希的协同过滤推荐算法之E^2LSH

    需要代码联系作者,不做义务咨询. 一.算法实现 基于p-stable分布,并以‘哈希技术分类’中的分层法为使用方法,就产生了E2LSH算法. E2LSH中的哈希函数定义如下: 其中,v为d维原始数据, ...

  3. Docker 监控实战

    如今,越来越多的公司开始使用 Docker 了,现在来给大家看几组数据: 2 / 3 的公司在尝试了 Docker 后最终使用了它 也就是说 Docker 的转化率达到了 67%,而转化市场也控制在 ...

  4. VS2005(vs2008,vs2010)使用map文件查找程序崩溃原因

    VS 2005使用map文件查找程序崩溃原因 一般程序崩溃可以通过debug,找到程序在那一行代码崩溃了,最近编一个多线程的程序,都不知道在那发生错误,多线程并发,又不好单行调试,终于找到一个比较好的 ...

  5. 在WIN32 DLL中使用MFC库遇到的问题

    今天写了一个DLL,DLL中用到的一个类里用到的MSXML的COM组件,所以在DLL中要包含afx.h头文件,也就不可避免的要用到MFC的类库了,但在编译时出现了错误:mfcs42d.lib(dllm ...

  6. ubuntu下如何设置主机名

    方法如下: 在终端输入 hostname 查看主机名主机名存放在/etc/hostname中 ,sudo gedit /etc/hostname 修改后保存/etc/hosts 还有一份 , sudo ...

  7. SGU 101 修改

    感谢这里. test4确实是个不连通的case,奇怪的是我用check函数跟if (check() == false)来判断这个case,当不连通时就死循环,得到的结果是不一样的,前者得到WA,后者得 ...

  8. POJ2993——Help Me with the Game(字符串处理+排序)

    Help Me with the Game DescriptionYour task is to read a picture of a chessboard position and print i ...

  9. 隐马尔科夫模型,第三种问题解法,维比特算法(biterbi) algorithm python代码

    上篇介绍了隐马尔科夫模型 本文给出关于问题3解决方法,并给出一个例子的python代码 回顾上文,问题3是什么, 下面给出,维比特算法(biterbi) algorithm 下面通过一个具体例子,来说 ...

  10. phpStorm 安装配置

    首先配置php解释器,进行相关设置: 配置nodejs支持 安装plugins nodejs. 问:如何修改模板的默认注释? 答:创建一个php文件,默认有: <?php/** * Create ...