第一次写blog。主要记录一下平时在实验室所进行的工作内容。(希望自己可以坚持每周来做个总结哈哈哈哈哈)
还是一枚小白,代码方面写的应该有很多问题。希望自己可以不断加油啦~
本项工作主要是修改capycha包中的image.py文件,再利用验证码自动生成的程序,同时生成不改变验证码字符形状的有背景和无背景文本验证码。
实验效果图如下:
image.py:该文件中代码主要描述文本验证码的页面元素构造。包括:字体、背景颜色、字体颜色、字符的旋转、页面元素中的噪点和干扰线等等。
1.保证两张验证码输出的字符的颜色、大小、旋转方式都相同。
2.保证文本验证码中一张背景为白色,另一张中背景颜色随机,干扰线、噪点也随机。
3.在生成文本验证码的程序中保证同时输出两张。
1.在生成过程中,由于文本验证码中的某些页面元素都是随机的产生的,因此如何保持两张验证码中某些元素的一致性。
2.为了生成一组对应的验证码,如何修改image.py的代码使其直接输出两种验证码。
1.在含有random的代码部分都保持不变。
2.将原有的一个返回变量im,改为两个返回变量im1(有背景),im2(无背景)。
1.class _Captcha()中的generate()函数:产生有背景和无背景验证码的两个输出返回。
def generate(self, chars, format='png'):
"""Generate an Image Captcha of the given characters.
:param chars: text to be generated.
:param format: image file format
"""
im = self.generate_image(chars)
out1 = BytesIO()
out2 = BytesIO()
im[0].save(out1, format=format)
im[1].save(out2, format=format)
out1.seek(0)
out2.seek(0)
return out1, out2
2.class ImageCaptcha()中create_captcha_image()函数:保证两张验证码产生的字符大小,颜色,旋转扭曲角度相同,并生成有背景和无背景的两种类型。
def create_captcha_image(self, chars, color, background1, background2):
"""Create the CAPTCHA image itself.
:param chars: text to be generated.
:param color: color of the text.
:param background: color of the background.
The color should be a tuple of 3 numbers, such as (0, 255, 255).
"""
image1 = Image.new('RGB', (self._width, self._height), background1)
image2 = Image.new('RGB', (self._width, self._height), background2)
draw1 = Draw(image1)
draw1 = Draw(image2)
def _draw_character(c):
font = random.choice(self.truefonts)
w, h = draw1.textsize(c, font=font)
dx = random.randint(0, 4)
dy = random.randint(0, 6)
im = Image.new('RGBA', (w + dx, h + dy))
Draw(im).text((dx, dy), c, font=font, fill=color)
# rotate
im = im.crop(im.getbbox())
im = im.rotate(random.uniform(-30, 30), Image.BILINEAR, expand=1)
# warp
dx = w * random.uniform(0.1, 0.3)
dy = h * random.uniform(0.2, 0.3)
x1 = int(random.uniform(-dx, dx))
y1 = int(random.uniform(-dy, dy))
x2 = int(random.uniform(-dx, dx))
y2 = int(random.uniform(-dy, dy))
w2 = w + abs(x1) + abs(x2)
h2 = h + abs(y1) + abs(y2)
data = (
x1, y1,
-x1, h2 - y2,
w2 + x2, h2 + y2,
w2 - x2, -y1,
)
im = im.resize((w2, h2))
im = im.transform((w, h), Image.QUAD, data)
return im
images = []
for c in chars:
if random.random() > 0.5:
images.append(_draw_character(" "))
images.append(_draw_character(c))
text_width = sum([im.size[0] for im in images])
width = max(text_width, self._width)
image1 = image1.resize((width, self._height))
image2 = image2.resize((width, self._height))
average = int(text_width / len(chars))
rand = int(0.25 * average)
offset = int(average * 0.1)
for im in images:
w, h = im.size
mask = im.convert('L').point(table)
image1.paste(im, (offset, int((self._height - h) / 2)), mask)
image2.paste(im, (offset, int((self._height - h) / 2)), mask)
offset = offset + w + random.randint(-rand, 0)
if width > self._width:
image1 = image1.resize((self._width, self._height))
image2 = image2.resize((self._width, self._height))
return image1, image2
def generate_image(self, chars):
"""Generate the image of the given characters.
:param chars: text to be generated.
"""
background1 = random_color(238, 255)
background2 = random_color(255, 255)
color1 = random_color(10, 220, random.randint(220, 220))
im1, im2 = self.create_captcha_image(chars, color1, background1, background2)
im2 = im2.filter(ImageFilter.SMOOTH)
self.create_noise_dots(im1, color1)
self.create_noise_curve(im1, color1)
im1 = im1.filter(ImageFilter.SMOOTH)
return im1, im2
image.py
:文本验证码页面元素修改
# coding: utf-8
"""
captcha.image
~~~~~~~~~~~~~
Generate Image CAPTCHAs, just the normal image CAPTCHAs you are using.
"""
import os
import random
from PIL import Image
from PIL import ImageFilter
from PIL.ImageDraw import Draw
from PIL.ImageFont import truetype
try:
from cStringIO import StringIO as BytesIO
except ImportError:
from io import BytesIO
try:
from wheezy.captcha import image as wheezy_captcha
except ImportError:
wheezy_captcha = None
DATA_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'data')
DEFAULT_FONTS = [os.path.join(DATA_DIR, 'DroidSansMono.ttf')]
if wheezy_captcha:
__all__ = ['ImageCaptcha', 'WheezyCaptcha']
else:
__all__ = ['ImageCaptcha']
table = []
for i in range( 256 ):
table.append( i * 1.97 )
class _Captcha(object):
def generate(self, chars, format='png'):
"""Generate an Image Captcha of the given characters.
:param chars: text to be generated.
:param format: image file format
"""
im = self.generate_image(chars)
out1 = BytesIO()
out2 = BytesIO()
im[0].save(out1, format=format)
im[1].save(out2, format=format)
out1.seek(0)
out2.seek(0)
return out1, out2
def write(self, chars, output, format='png'):
"""Generate and write an image CAPTCHA data to the output.
:param chars: text to be generated.
:param output: output destination.
:param format: image file format
"""
im = self.generate_image(chars)
return im.save(output, format=format)
class WheezyCaptcha(_Captcha):
"""Create an image CAPTCHA with wheezy.captcha."""
def __init__(self, width=200, height=75, fonts=None):
self._width = width
self._height = height
self._fonts = fonts or DEFAULT_FONTS
def generate_image(self, chars):
text_drawings = [
wheezy_captcha.warp(),
wheezy_captcha.rotate(),
wheezy_captcha.offset(),
]
fn = wheezy_captcha.captcha(
drawings=[
wheezy_captcha.background(),
wheezy_captcha.text(fonts=self._fonts, drawings=text_drawings),
wheezy_captcha.curve(),
wheezy_captcha.noise(),
wheezy_captcha.smooth(),
],
width=self._width,
height=self._height,
)
return fn(chars)
class ImageCaptcha(_Captcha):
"""Create an image CAPTCHA.
Many of the codes are borrowed from wheezy.captcha, with a modification
for memory and developer friendly.
ImageCaptcha has one built-in font, DroidSansMono, which is licensed under
Apache License 2. You should always use your own fonts::
captcha = ImageCaptcha(fonts=['/path/to/A.ttf', '/path/to/B.ttf'])
You can put as many fonts as you like. But be aware of your memory, all of
the fonts are loaded into your memory, so keep them a lot, but not too
many.
:param width: The width of the CAPTCHA image.
:param height: The height of the CAPTCHA image.
:param fonts: Fonts to be used to generate CAPTCHA images.
:param font_sizes: Random choose a font size from this parameters.
"""
def __init__(self, width=160, height=60, fonts=None, font_sizes=None):
self._width = width
self._height = height
self._fonts = fonts or DEFAULT_FONTS
self._font_sizes = font_sizes or (42, 50, 56)
self._truefonts = []
@property
def truefonts(self):
if self._truefonts:
return self._truefonts
self._truefonts = tuple([
truetype(n, s)
for n in self._fonts
for s in self._font_sizes
])
return self._truefonts
@staticmethod
def create_noise_curve(image, color):
w, h = image.size
x1 = random.randint(0, int(w / 5))
x2 = random.randint(w - int(w / 5), w)
y1 = random.randint(int(h / 5), h - int(h / 5))
y2 = random.randint(y1, h - int(h / 5))
points = [x1, y1, x2, y2]
end = random.randint(160, 200)
start = random.randint(0, 20)
Draw(image).arc(points, start, end, fill=color)
return image
@staticmethod
def create_noise_dots(image, color, width=3, number=30):
draw = Draw(image)
w, h = image.size
while number:
x1 = random.randint(0, w)
y1 = random.randint(0, h)
draw.line(((x1, y1), (x1 - 1, y1 - 1)), fill=color, width=width)
number -= 1
return image
def create_captcha_image(self, chars, color, background1, background2):
"""Create the CAPTCHA image itself.
:param chars: text to be generated.
:param color: color of the text.
:param background: color of the background.
The color should be a tuple of 3 numbers, such as (0, 255, 255).
"""
image1 = Image.new('RGB', (self._width, self._height), background1)
image2 = Image.new('RGB', (self._width, self._height), background2)
draw1 = Draw(image1)
draw1 = Draw(image2)
def _draw_character(c):
font = random.choice(self.truefonts)
w, h = draw1.textsize(c, font=font)
dx = random.randint(0, 4)
dy = random.randint(0, 6)
im = Image.new('RGBA', (w + dx, h + dy))
Draw(im).text((dx, dy), c, font=font, fill=color)
# rotate
im = im.crop(im.getbbox())
im = im.rotate(random.uniform(-30, 30), Image.BILINEAR, expand=1)
# warp
dx = w * random.uniform(0.1, 0.3)
dy = h * random.uniform(0.2, 0.3)
x1 = int(random.uniform(-dx, dx))
y1 = int(random.uniform(-dy, dy))
x2 = int(random.uniform(-dx, dx))
y2 = int(random.uniform(-dy, dy))
w2 = w + abs(x1) + abs(x2)
h2 = h + abs(y1) + abs(y2)
data = (
x1, y1,
-x1, h2 - y2,
w2 + x2, h2 + y2,
w2 - x2, -y1,
)
im = im.resize((w2, h2))
im = im.transform((w, h), Image.QUAD, data)
return im
images = []
for c in chars:
if random.random() > 0.5:
images.append(_draw_character(" "))
images.append(_draw_character(c))
text_width = sum([im.size[0] for im in images])
width = max(text_width, self._width)
image1 = image1.resize((width, self._height))
image2 = image2.resize((width, self._height))
average = int(text_width / len(chars))
rand = int(0.25 * average)
offset = int(average * 0.1)
for im in images:
w, h = im.size
mask = im.convert('L').point(table)
image1.paste(im, (offset, int((self._height - h) / 2)), mask)
image2.paste(im, (offset, int((self._height - h) / 2)), mask)
offset = offset + w + random.randint(-rand, 0)
if width > self._width:
image1 = image1.resize((self._width, self._height))
image2 = image2.resize((self._width, self._height))
return image1, image2
def generate_image(self, chars):
"""Generate the image of the given characters.
:param chars: text to be generated.
"""
background1 = random_color(238, 255)
background2 = random_color(255, 255)
color1 = random_color(10, 220, random.randint(220, 220))
im1, im2 = self.create_captcha_image(chars, color1, background1, background2)
#无背景im2中不添加干扰线和噪点#
im2 = im2.filter(ImageFilter.SMOOTH)
self.create_noise_dots(im1, color1)
self.create_noise_curve(im1, color1)
im1 = im1.filter(ImageFilter.SMOOTH)
return im1, im2
def random_color(start, end, opacity=None):
red = random.randint(start, end)
green = random.randint(start, end)
blue = random.randint(start, end)
if opacity is None:
return (red, green, blue)
return (red, green, blue, opacity)
captcha_setting.py
:设置字符类型,生成的图片大小、文件保存路径。
# -*- coding: UTF-8 -*-
import os
NUMBER = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
# ALPHABET = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
# ALPHABET_LITTLE = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
# ALL_CHAR_SET = NUMBER + ALPHABET + ALPHABET_LITTLE
ALL_CHAR_SET = NUMBER
ALL_CHAR_SET_LEN = len(ALL_CHAR_SET)
MAX_CAPTCHA = 4
# 图像大小
IMAGE_HEIGHT = 60
IMAGE_WIDTH = 160
#图像保存路径
BG_YES_PATH = 'dataset' + os.path.sep + 'bg_yes'
BG_NO_PATH = 'dataset' + os.path.sep + 'bg_no'
captcha_gen.py
:有背景和没有背景的文本验证码同时生成代码。
# -*- coding: UTF-8 -*-
from image import ImageCaptcha # pip install captcha
from PIL import Image
import random
import captcha_setting
import os
def random_captcha():
captcha_text = []
for i in range(captcha_setting.MAX_CAPTCHA):
c = random.choice(captcha_setting.ALL_CHAR_SET)
captcha_text.append(c)
return ''.join(captcha_text)
# 生成字符对应的验证码
def gen_captcha_text_and_image():
image = ImageCaptcha()
captcha_text = random_captcha()
image1, image2 = image.generate(captcha_text)
captcha_image1 = Image.open(image1)
captcha_image2 = Image.open(image2)
return captcha_text, captcha_image1, captcha_image2
if __name__ == '__main__':
count = 1#生成验证码对数量
path1 = captcha_setting.BG_YES_PATH
path2 = captcha_setting.BG_NO_PATH
if not os.path.exists(path1):
os.makedirs(path1)
if not os.path.exists(path2):
os.makedirs(path2)
for i in range(count):
now = str(int(time.time()))
text, image1, image2 = gen_captcha_text_and_image()
if (image1.size[0] == 160) and (image1.size[1] == 60):
filename = text + '.png'
image1.save(path1 + os.path.sep + filename)
print('saved %d : %s' % (i+1, filename))
if (image2.size[0] == 160) and (image2.size[1] == 60):
filename = text + '.png'
image2.save(path2 + os.path.sep + filename)
print('saved %d : %s' % (i+1, filename))