-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimage.py
243 lines (201 loc) · 7.52 KB
/
image.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# coding: utf-8
"""
captcha.image
~~~~~~~~~~~~~
Generate Image CAPTCHAs, just the normal image CAPTCHAs you are using.
"""
import os
import random
import numpy as np
import cv2
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']
class _Captcha(object):
def generate(self, chars):
"""Generate an Image Captcha of the given characters.
:param chars: text to be generated.
"""
im = self.generate_image(chars)
out = BytesIO()
im.save(out, format='png')
out.seek(0)
return out
def write(self, chars, output):
"""Generate and write an image CAPTCHA data to the output.
:param chars: text to be generated.
:param output: output destionation.
"""
im = self.generate_image(chars)
return im.save(output, format='png')
class WheezyCaptcha(_Captcha):
"""Create an image CAPTCHA with wheezy.captcha."""
def __init__(self, width=36, height=36, 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=36, height=36, fonts=None, font_sizes=None):
self._width = width
self._height = height
self._fonts = fonts or DEFAULT_FONTS
self._font_sizes = font_sizes or (46, 58, 68)
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(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=2, number=20):
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, background):
"""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).
"""
image = Image.new('RGB', (self._width, self._height), background)
draw = Draw(image)
def _draw_character(c):
font = random.choice(self.truefonts)
w, h = draw.textsize(c, font=font)
dx = random.randint(0, 4)
dy = random.randint(0, 6)
im = Image.new('RGB', (w + dx, h + dy), background)
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:
images.append(_draw_character(c))
text_width = sum([im.size[0] for im in images])
width = max(text_width, self._width)
image = image.resize((width, self._height))
average = int(text_width / len(chars))
rand = int(0.15 * average)
offset = int(average * 0.1)
for im in images:
w, h = im.size
mask = im.convert('L').point(lambda i: i * 1.97)
image.paste(im, (offset, int((self._height - h) / 2)), mask)
offset = offset + w + random.randint(-rand, rand)
return image
def generate_image(self, chars):
"""Generate the image of the given characters.
:param chars: text to be generated.
"""
#background = random_color(238, 255)
background = (255, 255, 255)
background = (0,0,0)
color = (255, 255, 255)
#color = random_color(0, 200, random.randint(220, 255))
im = self.create_captcha_image(chars, color, background)
self.create_noise_dots(im, color)
self.create_noise_curve(im, color)
im = im.filter(ImageFilter.SMOOTH)
return im
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)
for let in range(10):
for i in range(1000):
let = str(chr(let + 65))
image = ImageCaptcha(height = 36, width = 36, fonts=['Tahoma.ttf','Arial.ttf','Georgia.ttf','Verdana.ttf'],font_sizes=[30])
data = image.generate(let)
image.write(let, './capcha_chars/' + '%s_%d.png' % (let,i))