本文整理汇总了Python中captcha.image.ImageCaptcha.generate_image方法的典型用法代码示例。如果您正苦于以下问题:Python ImageCaptcha.generate_image方法的具体用法?Python ImageCaptcha.generate_image怎么用?Python ImageCaptcha.generate_image使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类captcha.image.ImageCaptcha
的用法示例。
在下文中一共展示了ImageCaptcha.generate_image方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: gen
# 需要导入模块: from captcha.image import ImageCaptcha [as 别名]
# 或者: from captcha.image.ImageCaptcha import generate_image [as 别名]
def gen(batch_size=32):
X = np.zeros((batch_size, height, width, 3), dtype=np.uint8)
y = [np.zeros((batch_size, n_class), dtype=np.uint8) for i in range(n_len)]
generator = ImageCaptcha(width=width, height=height)
while True:
for i in range(batch_size):
random_str = ''.join([random.choice(characters) for j in range(4)])
X[i] = generator.generate_image(random_str)
for j, ch in enumerate(random_str):
y[j][i, :] = 0
y[j][i, characters.find(ch)] = 1
yield X, y
示例2: gen_captcha
# 需要导入模块: from captcha.image import ImageCaptcha [as 别名]
# 或者: from captcha.image.ImageCaptcha import generate_image [as 别名]
def gen_captcha(self,batch_size = 50):
X = np.zeros([batch_size,self.height,self.width,1])
img = np.zeros((self.height,self.width),dtype=np.uint8)
Y = np.zeros([batch_size,self.char_num,self.classes])
image = ImageCaptcha(width = self.width,height = self.height)
while True:
for i in range(batch_size):
captcha_str = ''.join(random.sample(self.characters,self.char_num))
img = image.generate_image(captcha_str).convert('L') #转灰度
img = np.array(img.getdata())
X[i] = np.reshape(img,[self.height,self.width,1])/255.0 #归一化[60,160,1]
for j,ch in enumerate(captcha_str):
Y[i,j,self.characters.find(ch)] = 1
Y = np.reshape(Y,(batch_size,self.char_num*self.classes))
yield X,Y
示例3: generate_image_sets_for_single_digit
# 需要导入模块: from captcha.image import ImageCaptcha [as 别名]
# 或者: from captcha.image.ImageCaptcha import generate_image [as 别名]
def generate_image_sets_for_single_digit(nb_sample=SAMPLE_SIZE, single_digit_index=0, fonts=None):
captcha = ImageCaptcha(fonts=fonts) if fonts else ImageCaptcha()
# print DIGIT_FORMAT_STR
labels = []
images = []
for i in range(0, nb_sample):
digits = 0
last_digit = INVALID_DIGIT
for j in range(0, DIGIT_COUNT):
digit = last_digit
while digit == last_digit:
digit = random.randint(0, 9)
last_digit = digit
digits = digits * 10 + digit
digits_as_str = DIGIT_FORMAT_STR % digits
labels.append(digits_as_str)
images.append(captcha.generate_image(digits_as_str))
digit_labels = list()
for digit_index in range(0, DIGIT_COUNT):
digit_labels.append(np.empty(nb_sample, dtype="int8"))
shape = (nb_sample, RGB_COLOR_COUNT, IMAGE_STD_HEIGHT, IMAGE_STD_WIDTH) if IS_TH else (nb_sample, IMAGE_STD_HEIGHT, IMAGE_STD_WIDTH, RGB_COLOR_COUNT)
digit_image_data = np.empty(shape, dtype="float32")
for index in range(0, nb_sample):
img = images[index].resize((IMAGE_STD_WIDTH, IMAGE_STD_HEIGHT), PIL.Image.LANCZOS)
# if index < SHOW_SAMPLE_SIZE:
# display.display(img)
img_arr = np.asarray(img, dtype="float32") / 255.0
if IS_TH:
digit_image_data[index, :, :, :] = np.rollaxis(img_arr, 2)
else:
digit_image_data[index, :, :, :] = img_arr
for digit_index in range(0, DIGIT_COUNT):
digit_labels[digit_index][index] = labels[index][digit_index]
x = digit_image_data
y = np_utils.to_categorical(digit_labels[single_digit_index], CLASS_COUNT)
return x, y
示例4: generate_image_sets_for_multi_digits
# 需要导入模块: from captcha.image import ImageCaptcha [as 别名]
# 或者: from captcha.image.ImageCaptcha import generate_image [as 别名]
def generate_image_sets_for_multi_digits(nb_sample=SAMPLE_SIZE):
captcha = ImageCaptcha()
labels = []
images = []
for i in range(0, nb_sample):
digits = 0
last_digit = INVALID_DIGIT
for j in range(0, DIGIT_COUNT):
digit = last_digit
while digit == last_digit:
digit = random.randint(0, 9)
last_digit = digit
digits = digits * 10 + digit
digits_as_str = DIGIT_FORMAT_STR % digits
labels.append(digits_as_str)
images.append(captcha.generate_image(digits_as_str))
digit_labels = np.empty((nb_sample, DIGIT_COUNT), dtype="int8")
shape = (nb_sample, IMAGE_STD_HEIGHT, IMAGE_STD_WIDTH, RGB_COLOR_COUNT)
digit_image_data = np.empty(shape, dtype="float32")
for index in range(0, nb_sample):
img = images[index].resize((IMAGE_STD_WIDTH, IMAGE_STD_HEIGHT), PIL.Image.LANCZOS)
img_arr = np.asarray(img, dtype="float32") / 255.0
digit_image_data[index, :, :, :] = img_arr
for digit_index in range(0, DIGIT_COUNT):
digit_labels[index][digit_index] = labels[index][digit_index]
x, y_as_num = digit_image_data, np.rollaxis(digit_labels, 1)
y = { (OUT_PUT_NAME_FORMAT % i ): to_categorical(y_as_num[i], CLASS_COUNT) for i in range(0, DIGIT_COUNT) }
# y = [to_categorical(y_as_num[i], CLASS_COUNT) for i in range(0, DIGIT_COUNT)]
return x, y
示例5: print
# 需要导入模块: from captcha.image import ImageCaptcha [as 别名]
# 或者: from captcha.image.ImageCaptcha import generate_image [as 别名]
# -*-coding=utf-8-*-
# @Time : 2018/8/21 13:47
# @File : captcha_usage.py
from captcha.image import ImageCaptcha
import matplotlib.pyplot as plt
import numpy as np
import random
import string
characters = string.digits + string.ascii_uppercase
print(characters)
width,height,n_len,n_class=170,80,4,len(characters)
generator = ImageCaptcha(width=width,height=height)
rand_str = ''.join([random.choice(characters) for i in range(n_len)])
img = generator.generate_image(rand_str)
plt.imshow(img)
plt.title(rand_str)
plt.show()
def gen(batch_size=32):
X = np.zeros((batch_size, height, width, 3), dtype=np.uint8)
y = [np.zeros((batch_size, n_class), dtype=np.uint8) for i in range(n_len)]
generator = ImageCaptcha(width=width, height=height)
while True:
for i in range(batch_size):
random_str = ''.join([random.choice(characters) for j in range(4)])
X[i] = generator.generate_image(random_str)
for j, ch in enumerate(random_str):
y[j][i, :] = 0
y[j][i, characters.find(ch)] = 1
示例6: gen_test_captcha
# 需要导入模块: from captcha.image import ImageCaptcha [as 别名]
# 或者: from captcha.image.ImageCaptcha import generate_image [as 别名]
def gen_test_captcha(self):
image = ImageCaptcha(width = self.width,height = self.height)
captcha_str = ''.join(random.sample(self.characters,self.char_num))
img = image.generate_image(captcha_str)
img.save(captcha_str + '.jpg')
示例7: PyCaptcha
# 需要导入模块: from captcha.image import ImageCaptcha [as 别名]
# 或者: from captcha.image.ImageCaptcha import generate_image [as 别名]
class PyCaptcha(BaseCaptcha):
def __init__(self, app):
from captcha.image import ImageCaptcha # pip install captcha
super().__init__(app)
self.app = app
self.fonts = app.config['PYCAPTCHA_FONTS']
self.prefix = app.config['PYCAPTCHA_CACHE_PREFIX']
self.chars = app.config['PYCAPTCHA_CHARS']
self.case_sens = app.config['PYCAPTCHA_CASE_SENSITIVE']
self.length = app.config['PYCAPTCHA_LENGTH']
rnd = utils_random.randrange(10**11, 10**12)
k = self.prefix + '_cache_test_{}'.format(rnd)
self.app.cache.set(k, rnd, timeout=10)
if self.app.cache.get(k) != rnd:
raise RuntimeError('PyCaptcha requires working cache (e.g. memcached)')
self.generator = ImageCaptcha(fonts=self.fonts)
self.bind_captcha_views()
def bind_captcha_views(self):
from flask import Blueprint
bp = Blueprint('pycaptcha', __name__)
bp.route('/captcha/<int:captcha_id>.jpg')(self.captcha_view)
self.app.register_blueprint(bp)
def _draw_and_save_image(self, captcha_id):
from io import BytesIO
solution = utils_random.random_string(self.length, self.chars)
with self.generator.generate_image(solution) as im: # class PIL.Image
data = BytesIO()
im.save(data, format='JPEG', quality=55)
data = data.getvalue()
tm = time.time()
k = self.prefix + str(captcha_id)
self.app.cache.set(k, [tm, data, solution], timeout=7200)
return data
def captcha_view(self, captcha_id):
from flask import abort, make_response
k = self.prefix + str(captcha_id)
result = self.app.cache.get(k)
if result is None:
abort(404)
if time.time() - result[0] > 1:
data = self._draw_and_save_image(captcha_id)
else:
data = result[1]
response = make_response(data)
response.headers['Content-Type'] = 'image/jpeg'
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "0"
response.headers['Cache-Control'] = 'public, max-age=0'
return response
def generate(self, lazy=True):
captcha_id = utils_random.randrange(10**11, 10**12)
k = 'pycaptcha_{}'.format(captcha_id)
self.app.cache.set(k, [0, b'', ''], timeout=7200)
if self.app.cache.get(k) != [0, b'', '']:
raise RuntimeError('PyCaptcha requires working cache (e.g. memcached)')
if not lazy:
self._draw_and_save_image(captcha_id)
return {'cls': 'mini_fiction.captcha.PyCaptcha', 'pycaptcha_id': str(captcha_id)}
def get_fields(self):
return ('captcha_id', 'captcha_solution')
def check(self, form):
captcha_id = form.get('captcha_id')
solution = form.get('captcha_solution')
if isinstance(captcha_id, str):
if captcha_id.isdigit():
captcha_id = int(captcha_id)
if not captcha_id or not solution:
return False
if not isinstance(solution, str) or len(solution) > 254 or not isinstance(captcha_id, int):
return False
k = self.prefix + str(captcha_id)
result = self.app.cache.get(k)
#.........这里部分代码省略.........