Python生成数字图片代码分享


Posted in Python onOctober 31, 2017

本文向大家分享了几段Python生成数字图片的代码,喜欢的朋友可以参考。具体如下:

最终版本

# -*- coding:utf-8 -*-
from PIL import Image,ImageFont,ImageDraw,ImageFilter
import random
import os
import time
class Code(object):
  def __init__(self, imgSize=(35,35),\
    fontSize=25, bgColor=(255,)*4, fontColor=(0,0,0)):
    self.imgSize = imgSize
    self.fontSize = fontSize
    self.bgColor = bgColor
    self.fontColor = fontColor
  def setFontSize(self, size):
    self.fontSize = size;
  def getDigit(self, digit):
    return str(digit)
  def getPannel(self):
    pannel = Image.new('RGBA',self.imgSize,self.bgColor)
    return pannel
  def getFont(self, fontFile='./Arial.ttf'):
    return ImageFont.truetype(fontFile, self.fontSize)
  def getTextPos(self, digit, font):
    text = self.getDigit(digit)
    textWidth,textHeight = font.getsize(text);
    imgWidth,imgHeight = self.imgSize
    textPos = ((imgWidth-textWidth)/2, (imgHeight-textHeight)/2)
    return textPos
  def rotateImg(self,image,angle=0, expand=0):
    rot = image.rotate(angle, expand)
    fff = Image.new('RGBA',rot.size,self.bgColor)
    image = Image.composite(rot, fff, rot)
    return image
  def createImg(self, digit, font, angle):
    codeImg = Image.new('RGBA',self.imgSize,self.bgColor)
    draw = ImageDraw.Draw(codeImg);
    text = self.getDigit(digit)
    textPos = self.getTextPos(digit, font)
    draw.text(xy=textPos,text=text,fill=self.fontColor,font=font)
    codeImg = self.rotateImg(codeImg,angle)
    return codeImg
  def saveImg(self, img, savePath, imgName):
    img.save(savePath+'/'+imgName)
def createPath(path):
  if not os.path.exists(path):
    os.makedirs(path)
def createImages(code,rootPath='./images',digitList=range(10), fontSizeList=range(18,30),\
  angleList=[(45,90),(-45,45),(-45,-90)]):
  for index,angles in enumerate(angleList):
    if index==0:
      angleRange = '-90_-45'
    elif index == 1:
      angleRange = '-45_45'
    else:
      angleRange = '45_90'
    anglepath = os.path.join(rootPath, angleRange)
    createPath(anglepath)
    for digit in digitList:
      digitpath = os.path.join(anglepath, 'x'+str(digit))
      createPath(digitpath)
      for size in fontSizeList:
        angle = round(random.uniform(angles[0], angles[1]),5)
        code.setFontSize(size)
        imgName = str(digit)+'_'+str(size)+'_'+str(angle)+'.jpg'
        img = code.createImg(digit, code.getFont(),angle)
        code.saveImg(img, digitpath, imgName)

if __name__ == '__main__':
  imagesPath = './images'
  if os.path.exists(imagesPath):
    os.system('rm -rf '+imagesPath)
  os.mkdir(imagesPath)
  code = Code()
  for i in range(1000):
    createImages(code)
  # test ...
  # code = Code()
  # img = code.createImg(5,code.getFont(),0)
  # code.saveImg(img, savePath, 'test.jpg')
  # img.show()
  print 'hello'
# -*- coding:utf-8 -*-
from PIL import Image,ImageFont,ImageDraw,ImageFilter
import random
import os
class Captcha(object):
  def __init__(self,size=(20,24),fontSize=20):
    self.font = ImageFont.truetype('./fonts/Arial.ttf',fontSize)
    self.size = size
    self.image = Image.new('RGBA',self.size,(255,)*4)
    # self.texts = self.randNum(1)
    self.text = ''
  def rotate(self, angle):
    # rot = self.image.rotate(random.randint(-10,10),expand=0)
    rot = self.image.rotate(angle,expand=0)
    fff = Image.new('RGBA',rot.size,(255,)*4)
    self.image = Image.composite(rot,fff,rot)
  def randColor(self):
    self.fontColor = (random.randint(0,250),random.randint(0,250),random.randint(0,250))
  # def randNum(self,bits):
  #   return ''.join(str(random.randint(0,9)) for i in range(bits))
  def setNum(self, num):
    return num;
  def write(self,text,x,y):
    draw = ImageDraw.Draw(self.image)
    draw.text((x,y),text,fill=self.fontColor,font=self.font)
  def writeNum(self, num, angle):
    x = 2
    y = -2
    self.text = num
    self.fontColor = (0, 0, 0)
    self.write(num, x, y)
    self.rotate(angle)
    return self.text
    # character
    # xplus = 15
    # for text in self.texts:
      # self.randColor()
      # self.fontColor = (0, 0, 0)
      # self.write(text, x, y)
      # self.rotate(angle)
      # self.rotate(random.randint(-10,10))
      # x += xplus
    # return self.texts
  def save(self, save_path):
    # self.image.save('captcha.jpg')
    self.image.save(save_path)
pic_root_path = './pic'
if not os.path.exists(pic_root_path):
  os.mkdir(pic_root_path)
angles = [(45,90),(-45,45),(-90,-45)]
for i in range(10):
  pic_num_path = os.path.join(pic_root_path, 'pic'+str(i))
  if not os.path.exists(pic_num_path):
    os.mkdir(pic_num_path)
  for angle_i in angles:
    angle_name = str(angle_i[0])+'_'+str(angle_i[1])
    pic_angle_path = os.path.join(pic_num_path, angle_name)
    if not os.path.exists(pic_angle_path):
      os.mkdir(pic_angle_path)
    for angle in range(angle_i[0], angle_i[1]):
      for fontsize in range(25,28):
        img = Captcha(size=(20, 24), fontSize=fontsize)
        num = img.writeNum(str(i), angle)
        img_name = str(i)+'_'+str(fontsize)+'_'+str(angle)+'.bmp'
        save_path = os.path.join(pic_angle_path, img_name)
        img.save(save_path)

  # img = Captcha()
  # num = img.writeNum(str(i), random.randint(-90,-45))
  # img_name = str(i)+'.jpg'
  # pic_path = './pic'+str(i)
  # if not os.path.exists(pic_path):
  #   os.mkdir(pic_path)
  # save_path = os.path.join(pic_path, img_name)
  # save_path = os.path.join(pic_root_path, save_path)
  # img.save(save_path)
# img.image.show()
# img.save()

随机生成各种size和旋转角度的单个数字图片

# -*- coding:utf-8 -*-
from PIL import Image,ImageFont,ImageDraw,ImageFilter
import random
import os
import time
class Captcha(object):
  def __init__(self,size=(20,24),fontSize=20):
    self.font = ImageFont.truetype('./fonts/Arial.ttf',fontSize)
    self.size = size
    self.image = Image.new('RGBA',self.size,(255,)*4)
    self.text = ''
  def rotate(self, angle):
    rot = self.image.rotate(angle,expand=0)
    fff = Image.new('RGBA',rot.size,(255,)*4)
    self.image = Image.composite(rot,fff,rot)
  def randColor(self):
    self.fontColor = (random.randint(0,250),random.randint(0,250),random.randint(0,250))

  def setNum(self, num):
    return num;
  def write(self,text,x,y):
    draw = ImageDraw.Draw(self.image)
    draw.text((x,y),text,fill=self.fontColor,font=self.font)
  def writeNum(self, num, angle):
    x = 2
    y = -2
    self.text = num
    self.fontColor = (0, 0, 0)
    self.write(num, x, y)
    self.rotate(angle)
    return self.text
  def save(self, save_path):
    # self.image = self.image.filter(ImageFilter.EDGE_ENHANCE_MORE) #滤镜,边界加强
    self.image.save(save_path)
pic_root_path = './pic'
if not os.path.exists(pic_root_path):
  os.mkdir(pic_root_path)
angles = [(45,90),(-45,45),(-90,-45)]
for i in range(10):
  pic_num_path = os.path.join(pic_root_path, 'x'+str(i))
  if not os.path.exists(pic_num_path):
    os.mkdir(pic_num_path)
  for angle_i in angles:
    angle_name = str(angle_i[0])+'_'+str(angle_i[1])
    pic_angle_path = os.path.join(pic_num_path, angle_name)
    if not os.path.exists(pic_angle_path):
      os.mkdir(pic_angle_path)
    for fontsize in range(25,29):
      for j in range(2500):
        # Keep 5 decimal places
        angle = round(random.uniform(angle_i[0], angle_i[1]),5) 
        img = Captcha(size=(20, 24), fontSize=fontsize)
        num = img.writeNum(str(i), angle)
        img_name = 'x'+str(j)+'_'+str(fontsize)+'_'+str(angle)+'_'+str(num)+'.jpg'
        save_path = os.path.join(pic_angle_path, img_name)
        img.save(save_path)

文字居中

# -*- coding:utf-8 -*-
from PIL import Image,ImageFont,ImageDraw,ImageFilter
import random
import os
import time
imgWidth = 20
imgHeight = 24
fontSize = 28
backGroundColor = (255,)*4
fontColor = (0,)*3
text = '0'
font = ImageFont.truetype('./Arial.ttf', fontSize)
codeimg = Image.new('RGBA',(imgWidth,imgHeight), backGroundColor)
imagePath = './codes'
if not os.path.exists(imagePath):
  os.mkdir(imagePath)
textWidth, textHeight = font.getsize(text)
textLeft = (imgWidth-textWidth)/2
textTop = (imgHeight-textHeight)/2
draw = ImageDraw.Draw(codeimg)
draw.text(xy=(textLeft,textTop),text=text,fill=fontColor,font=font)
rot = codeimg.rotate(90,expand=0)
codeimg.rotate
fff = Image.new('RGBA', rot.size,backGroundColor)
codeimg = Image.composite(rot, fff, rot)
codeimg.show()
# codeimg.save('./codes/test.jpg')

以上就是本文关于Python生成数字图片代码分享的全部内容,希望对大家有所帮助。欢迎参阅:Python列表删除的三种方法代码分享Python文件的读写和异常代码示例等,有问题可以随时留言,欢迎大家交流讨论。

Python 相关文章推荐
Python实现LRU算法的2种方法
Jun 24 Python
python通过加号运算符操作列表的方法
Jul 28 Python
Python安装Numpy和matplotlib的方法(推荐)
Nov 02 Python
python处理csv中的空值方法
Jun 22 Python
Python数据类型之List列表实例详解
May 08 Python
python 给图像添加透明度(alpha通道)
Apr 09 Python
基于Python的身份证验证识别和数据处理详解
Nov 14 Python
在Python中实现字典反转案例
Dec 05 Python
Python3 使用pip安装git并获取Yahoo金融数据的操作
Apr 08 Python
bat批处理之字符串操作的实现
Mar 16 Python
Python学习之时间包使用教程详解
Mar 21 Python
PYTHON使用Matplotlib去实现各种条形图的绘制
Mar 22 Python
python使用标准库根据进程名如何获取进程的pid详解
Oct 31 #Python
Python列表删除的三种方法代码分享
Oct 31 #Python
Python文件的读写和异常代码示例
Oct 31 #Python
Python网络编程详解
Oct 31 #Python
Python中enumerate函数代码解析
Oct 31 #Python
python数据类型判断type与isinstance的区别实例解析
Oct 31 #Python
python中requests库session对象的妙用详解
Oct 30 #Python
You might like
php不写闭合标签的好处
2014/03/04 PHP
php+webSoket实现聊天室示例代码(附源码)
2017/02/17 PHP
css3实现背景模糊的三种方式
2021/03/09 HTML / CSS
js下用eval生成JSON对象
2010/09/17 Javascript
JQuery与JS里submit()的区别示例介绍
2014/02/17 Javascript
javascript中bind函数的作用实例介绍
2014/09/28 Javascript
JavaScript实现把rgb颜色转换成16进制颜色的方法
2015/06/01 Javascript
Javascript验证方法大全
2015/09/21 Javascript
jquery实现全屏滚动
2015/12/28 Javascript
iscroll.js的上拉下拉刷新时无法回弹的解决方法
2016/02/18 Javascript
Node.js中JavaScript操作MySQL的常用方法整理
2016/03/01 Javascript
引用jquery框架后出错的解决方法
2016/08/09 Javascript
Angular2  NgModule 模块详解
2016/10/19 Javascript
基于百度地图实现产品销售的单位位置查看功能设计与实现
2016/10/21 Javascript
详解vue+css3做交互特效的方法
2017/11/20 Javascript
Vue入门之animate过渡动画效果
2018/04/08 Javascript
javascript数据结构之多叉树经典操作示例【创建、添加、遍历、移除等】
2018/08/01 Javascript
layui type2 通过url给iframe子页面传值的例子
2019/09/06 Javascript
实例讲解React 组件
2020/07/07 Javascript
vue 导航锚点_点击平滑滚动,导航栏对应变化详解
2020/08/10 Javascript
python下如何让web元素的生成更简单的分析
2008/07/17 Python
Python中getattr函数和hasattr函数作用详解
2016/06/14 Python
python 求某条线上特定x值或y值的点坐标方法
2019/07/09 Python
基于SpringBoot构造器注入循环依赖及解决方式
2020/04/26 Python
Python gevent协程切换实现详解
2020/09/14 Python
python 使用paramiko模块进行封装,远程操作linux主机的示例代码
2020/12/03 Python
CSS3 文字动画效果
2020/11/12 HTML / CSS
Math.round(11.5)等於多少? Math.round(-11.5)等於多少?
2015/01/27 面试题
解释下列WebService名词:WSDL、SOAP、UDDI
2012/06/22 面试题
高中生毕业自我鉴定
2013/10/10 职场文书
设备售后服务承诺书
2014/05/30 职场文书
企业年检委托书范本
2014/10/14 职场文书
学校师德师风整改措施
2014/10/27 职场文书
2014年双拥工作总结
2014/11/21 职场文书
2015年派出所民警工作总结
2015/04/24 职场文书
银行求职信怎么写
2019/06/20 职场文书