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 linecache.getline()读取文件中特定一行的脚本
Sep 06 Python
一个Python最简单的接口自动化框架
Jan 02 Python
python3+PyQt5实现拖放功能
Apr 24 Python
对python中for、if、while的区别与比较方法
Jun 25 Python
Python类的继承用法示例
Jan 31 Python
解决Django加载静态资源失败的问题
Jul 28 Python
Django中URL的参数传递的实现
Aug 04 Python
python中如何实现将数据分成训练集与测试集的方法
Sep 13 Python
python中count函数简单用法
Jan 05 Python
带你彻底搞懂python操作mysql数据库(cursor游标讲解)
Jan 06 Python
pyftplib中文乱码问题解决方案
Jan 11 Python
pycharm配置QtDesigner的超详细方法
Jan 25 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中使用灵巧的体系结构
2006/10/09 PHP
Codeigniter通过SimpleXML将xml转换成对象的方法
2015/03/19 PHP
php读取torrent种子文件内容的方法(测试可用)
2016/05/03 PHP
利用jQuery简单实现产品展示图片左右滚动功能(示例代码)
2014/01/02 Javascript
JQuery遍历json数组的3种方法
2014/11/08 Javascript
jquery中trigger()无法触发hover事件的解决方法
2015/05/07 Javascript
在JavaScript中操作时间之getYear()方法的使用教程
2015/06/11 Javascript
JS中innerHTML和pasteHTML的区别实例分析
2016/06/22 Javascript
js制作可以延时消失的菜单
2017/01/13 Javascript
详解如何将angular-ui的图片轮播组件封装成一个指令
2017/05/09 Javascript
浅析 NodeJs 的几种文件路径
2017/06/07 NodeJs
vue项目中使用axios上传图片等文件操作
2017/11/02 Javascript
vue+element表格导出为Excel文件
2019/09/26 Javascript
JS代码触发事件代码实例
2020/01/02 Javascript
Python3实现的腾讯微博自动发帖小工具
2013/11/11 Python
python实现批量改文件名称的方法
2015/05/25 Python
python中返回矩阵的行列方法
2018/04/04 Python
Python中的TCP socket写法示例
2018/05/11 Python
python利用ffmpeg进行录制屏幕的方法
2019/01/10 Python
python基于gevent实现并发下载器代码实例
2019/11/01 Python
Python迷宫生成和迷宫破解算法实例
2019/12/24 Python
Python如何实现在字符串里嵌入双引号或者单引号
2020/03/02 Python
Steiff台湾官网:德国金耳釦泰迪熊
2019/12/26 全球购物
影视艺术学院毕业生自荐信
2013/11/13 职场文书
高考备战决心书
2014/03/11 职场文书
护理专业学生职业生涯规划范文
2014/03/11 职场文书
三八红旗手先进事迹材料
2014/05/13 职场文书
记账会计岗位职责
2014/06/16 职场文书
上海世博会口号
2014/06/19 职场文书
双拥工作宣传标语
2014/06/26 职场文书
会计工作能力自我评价
2015/03/05 职场文书
刑事起诉书范文
2015/05/19 职场文书
国家助学金受助感言
2015/08/01 职场文书
导游词之重庆渣滓洞
2020/01/08 职场文书
【DOTA2】当街暴打?PSG LGD vs VG - DPC 2022 WINTER TOUR CN
2022/04/02 DOTA
java版 联机五子棋游戏
2022/05/04 Java/Android