标签:自动生成 自己实现 生成 ret style enumerate 自己 object fill
网上有很多,却都不够简单干脆,自己实现了一个。但可惜字体旋转未能成功。
#!/usr/bin/env python # coding=utf-8 from PIL import Image, ImageDraw, ImageFont import os, random from prepare import clearNoise class ImageCaptcha(object): def __init__(self, size=(200, 60)): bgColor = self.random_color(200, 255) self.image = Image.new(‘RGB‘, size, bgColor) def random_color(self, minc, maxc): return (random.randint(minc, maxc), random.randint(minc, maxc), random.randint(minc, maxc)) def gen_text(self, cnt=6): seq = ‘23456789ABCDEFGHIJKLMNOPQRSTUVWXYZ‘ text = [random.choice(seq) for i in range(cnt)] return ‘‘.join(text) def draw_text(self, pos, txt): draw = ImageDraw.Draw(self.image) fontSize = random.choice([38, 42, 56]) # font = ImageFont.truetype(‘DroidSerif-Bold.ttf‘, fontSize) font = ImageFont.truetype(‘Arimo-Bold.ttf‘, fontSize) fontColor = self.random_color(0, 150) draw.text(pos, txt, font=font, fill=fontColor) def rotate(self, angle): self.image = self.image.rotate(random.randint(-1*angle, angle), expand=0) def gen_captcha_image(self, text): for i, txt in enumerate(text): x = 8 + i * 30 + random.randint(-10, 10) y = random.randint(0, 10) self.draw_text((x, y), txt) # self.rotate(5) return self.image def clear_noise(path): fnames = [os.path.join(path, fname) for fname in os.listdir(path) if fname.endswith(‘jpg‘)] for fname in fnames: img = clearNoise(fname) img.save(‘auto/clearNoise/%s‘ % fname.split(‘/‘)[-1]) print img.size, fname, ‘done‘ if __name__== ‘__main__‘: for i in range(20): test = ImageCaptcha() text = test.gen_text(6) img = test.gen_captcha_image(text) img.save(‘auto/origin/%s_%d.jpg‘ % (text, i))
标签:自动生成 自己实现 生成 ret style enumerate 自己 object fill
原文地址:http://www.cnblogs.com/jkmiao/p/6379178.html