Example #1
0
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
Example #2
0
def random_img(captcha_len=4, img_w=width, img_h=height):
    """
    利用ImageCaptcha库生成随机验证码图片
    :param img_h:
    :param img_w:
    :param captcha_len: 验证码长度
    :return: 验证码图片和内容
    """
    generator = ImageCaptcha(width=img_w,
                             height=img_h,
                             fonts=[os.path.join(file_path, 'kongxin.ttf')])
    # generator = ImageCaptcha(width=img_w, height=img_h)
    random_str = ''.join([random.choice(alphabet) for j in range(captcha_len)])
    captchas = random_str
    img = generator.generate_image(random_str)
    return img, captchas
Example #3
0
def gen123():
    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)
            # 把Y设置成4个列表
            for j, ch in enumerate(random_str):
                y[j][i, :] = 0
                y[j][i, characters.find(ch)] = 1
        yield X, y
def captcha():
    letters = string.ascii_uppercase
    length = random.randint(4, 5)
    global captcha_text
    global captcha_img
    captcha_text = ''.join(random.choice(letters) for i in range(length))

    img = ImageCaptcha(width=160, height=60, fonts=None, font_sizes=None)
    image = img.generate_image(captcha_text)
    image.save('captcha.jpg')
    open_image = Image.open("captcha.jpg")
    photo = ImageTk.PhotoImage(open_image)
    captcha_img = tk.Label(image=photo)
    captcha_img.image = photo
    captcha_img.pack()
    captcha_img.place(y=120, x=100)
Example #5
0
    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
                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
Example #6
0
def gen(batch_size=128):
    X = np.zeros((batch_size, width, height, 3), dtype=np.uint8)
    y = np.zeros((batch_size, n_len), dtype=np.uint8)
    generator = ImageCaptcha(width=width, height=height)
    while True:
        for i in range(batch_size):
            random_str = ''.join(
                [random.choice(characters) for j in range(n_len)])
            X[i] = np.array(generator.generate_image(random_str)).transpose(
                1, 0, 2)
            y[i] = [characters.find(x) for x in random_str]
        yield [
            X, y,
            np.ones(batch_size) * rnn_length,
            np.ones(batch_size) * n_len
        ], np.ones(batch_size)
Example #7
0
def gen_sample(height=80, width=170, batch_size=1, n_class=36):
    print("生成样本")
    X = np.zeros((batch_size, height, width, 3), dtype=np.float)
    Y = [np.zeros((batch_size, n_class), dtype=np.uint8) for i in range(4)]
    # 生成器
    generator = ImageCaptcha(height=height, width=width)
    while 1:
        for i in range(batch_size):
            code, raw, = random_code()
            generate_code = generator.generate_image(code)
            X[i] = np.array(generate_code).astype('float32') / 255

            for j, ch in enumerate(code):
                Y[j][i, :0] = 0
                Y[j][i, raw.find(ch)] = 1
        yield X, Y, raw, generate_code, code
Example #8
0
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_LENGTH)
    ]
    generator = ImageCaptcha(width=WIDTH, height=HEIGHT)
    while True:
        for i in range(batch_size):
            random_str = "".join(
                [random.choice(characters) for k in range(N_LENGTH)])
            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
Example #9
0
def gen_code(batch_size=32):
    X = np.zeros((batch_size, height * 4, width * 4, 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(n_len)])
            img = generator.generate_image(random_str)
            img = Image__.fromarray(
                cv2.resize(np.asarray(img), (width * 4, height * 4)))
            X[i] = img
            for j, ch in enumerate(random_str):
                y[j][i, :] = 0
                y[j][i, characters.find(ch)] = 1
        yield np.array(X), y
def gen(batch_size=128):
    X = np.zeros((batch_size, height, width, 3), dtype=np.uint8)
    y = np.zeros((batch_size, n_len), dtype=np.uint8)
    while True:
        generator = ImageCaptcha(width=width, height=height)
        for i in range(batch_size):
            random_str = ''.join([random.choice(characters) for j in range(4)])
            X[i] = np.array(generator.generate_image(random_str))
            # X[i]=np.transpose(X[i],(2,1,0))
            # 长n_len  下标表示
            y[i] = [characters.find(x) for x in random_str]
        yield [
            X.transpose((0, 3, 2, 1)), y,
            np.ones(batch_size) * int(conv_shape[1] - 2),
            np.ones(batch_size) * n_len
        ], np.ones(batch_size)
Example #11
0
def gen(height=gConfig['hight'],
        width=gConfig['width'],
        batch_size=1,
        nclass=gConfig['num_datasetclasses']):
    X = np.zeros((batch_size, height, width, 3), dtype=np.float)
    y = [np.zeros((batch_size, nclass), dtype='uint8') for i in range(4)]
    generator = ImageCaptcha(height=height, width=width)
    while True:
        for i in range(batch_size):
            random_str, raw = randomCode()
            genCode = generator.generate_image(random_str)
            X[i] = np.array(genCode).astype('float32') / 255.
            for j, ch in enumerate(random_str):
                y[j][i, :] = 0
                y[j][i, raw.find(ch)] = 1
        yield X, y, raw, genCode, random_str
Example #12
0
def main():
    dirs = [TRAIN_DIR, VAL_DIR]
    for d in dirs:
        if not os.path.exists(d):
            os.mkdir(d)

        if d == TRAIN_DIR:
            step = 10000
        else:
            step = 1000

        for ns in range(step):
            file_name = create()
            img = ImageCaptcha(width=IMG_WIDTH, height=IMG_HEIGHT)
            image = img.generate_image(file_name)
            image.save(f'{d}/{file_name}_1.png')
def gen(batch_size=32):
	# 
	X=np.zeros((batch_size,height,width,3),dtype=np.uint8)
	# one-hot 
	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(n_len)])
			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
		# 将图片输入转为th格式输入
		# X=np.transpose(X,(0,3,1,2))
		yield np.transpose(X,(0,3,1,2)),y
Example #14
0
    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
Example #15
0
def gen_image():
    image_width = 100
    image_height = 60
    origin_dir = './images/origin/'
    char_set = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
    char_set_len = len(char_set)
    captcha_len = 4
    generator = ImageCaptcha(width=100, height=60, fonts=['images/captcha.ttf'])
    for i in range(20000):
        print("正在生成第%d张图片"%(i + 1))
        random_str = ''.join(random.choice(char_set) for i in range(captcha_len))
        random_num = random.randint(10000,99999)
        img = generator.generate_image(random_str)
        file_name = random_str + "_" + str(random_num) + ".jpg"
        img.save(origin_dir + file_name)
    print("ok")
def gen(batch_size=32):
    X = np.zeros((batch_size, height, width, 3), dtype=np.uint8)
    y = np.zeros((batch_size, n_len * n_class), dtype=np.uint8)
    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, c in enumerate(random_str):
                index = j * n_class + CAPTCHA_LIST.index(c)
                y[i][index] = 1
  #          for j, ch in enumerate(random_str):
   #             y[i]
 #               y[j][i, :] = 0
 #               y[j][i, characters.find(ch)] = 1
        yield X, y
Example #17
0
def generate_image_sets_for_multi_digits(nb_sample=SAMPLE_SIZE, 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 = np.empty((nb_sample, DIGIT_COUNT), 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[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):
         np_utils.to_categorical(y_as_num[i], CLASS_COUNT)
         for i in range(0, DIGIT_COUNT)}

    return x, y
Example #18
0
    def generateVerificationCode(self, len=4):
        ''' 随机生成4位的验证码 '''
        list_code = []
        for i in range(10):  # 0-9数字
            list_code.append(str(i))
        for i in range(65, 91):  # 对应从“A”到“Z”的ASCII码
            list_code.append(chr(i))
        for i in range(97, 123):  #对应从“a”到“z”的ASCII码
            list_code.append(chr(i))
        slice = random.sample(list_code, len)  # 从list中随机获取4个元素,作为一个验证码返回
        verification_code = ''.join(slice)  # list to str

        img = ImageCaptcha()
        image_code = img.generate_image(verification_code)
        pixmap_image_code = image_code.toqpixmap()

        return verification_code, pixmap_image_code
Example #19
0
 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')
     # X:其 shape 为 [ 1, height, width, 1 ],1 表示每批次多少个训练数据,height ,width 表示验证码图片的高和宽,1 表示这是1个通道的黑白图片。
     # Y:X 中每个训练数据属于哪一类验证码,其形状为 [ 1, class ] ,对验证码中每个字符进行 One-Hot 编码,所以 class 大小为 4*62
     X = np.zeros([1, self.height, self.width, 1])
     Y = np.zeros([1, self.char_num, self.classes])
     img = img.convert('L')
     img = np.array(img.getdata())
     X[0] = np.reshape(img, [self.height, self.width, 1]) / 255.0
     for j, ch in enumerate(captcha_str):
         Y[0, j, self.characters.find(ch)] = 1
     Y = np.reshape(Y, (1, self.char_num * self.classes))
     return X, Y
Example #20
0
def generate_test_data(batch_size):
    img_generator = ImageCaptcha()
    while True:
        test_labels_batch = []
        test_imgs_batch = []
        length = random.randint(4, 7)
        for _ in range(batch_size):
            char = ''.join([random.choice(chars) for _ in range(length)])
            img = img_generator.generate_image(char)
            img = np.asarray(img)
            test_labels_batch.append(char)
            h = 32
            w = int(img.shape[1] * 32 / img.shape[0])
            img_gray = cv2.cvtColor(cv2.resize(img, (w, h)),
                                    cv2.COLOR_BGR2GRAY)
            test_imgs_batch.append(img_gray)
        yield ([np.array(test_imgs_batch), np.array(test_labels_batch)])
Example #21
0
class CaptchaSequence(Sequence):
    def __init__(self,
                 batch_size,
                 steps,
                 width=160,
                 height=60,
                 n_capt=4,
                 include_char=False):
        """
        :param batch_size: batch size
        :param steps: step nums
        :param width: the width of captcha image
        :param height: the height of captcha image
        :param n_capt: captcha length, Default is 4
        :param include_char: whether including english character. Default is False
        """
        self.batch_size = batch_size
        self.steps = steps
        self.width = width
        self.height = height
        self.n_capt = n_capt
        self.include_char = include_char
        self.generator = ImageCaptcha(width=self.width, height=self.height)
        self.characters = get_captcha_str_map(include_char=include_char)
        self.n_char = len(self.characters)  # character type num

    def __len__(self):
        return self.steps

    def __getitem__(self, index):
        X = np.zeros((self.batch_size, self.height, self.width, 3),
                     dtype=np.float32)
        Y = [
            np.zeros((self.batch_size, self.n_char), dtype=np.uint8)
            for _i in range(self.n_capt)
        ]

        for _i in range(self.batch_size):
            captcha_string = random_captcha_string(
                length=self.n_capt, include_char=self.include_char)
            X[_i] = np.array(
                self.generator.generate_image(captcha_string)) / 255.0
            for _j, ch in enumerate(captcha_string):
                Y[_j][_i, self.characters.find(ch)] = 1

        return X, Y
Example #22
0
def gen_training_data(output_dir, num_samples):
    min_chars = 4
    max_chars = 5
    char_set = string.ascii_letters + string.digits

    image_gen = ImageCaptcha()
    for n in range(num_samples):
        captcha_length = random.choice(range(min_chars, max_chars + 1))
        captcha_text = ''
        for c in range(captcha_length):
            captcha_text += random.choice(char_set)

        gen_result = image_gen.generate_image(captcha_text, for_training=True)
        target = gen_result["final"]
        target.save(os.path.join(output_dir, f'{captcha_text}.png'))

        label = []

        for c, char_img in enumerate(gen_result["char_onlys"]):
            left = -1
            right = -1
            top = -1
            bottom = -1

            for x in range(char_img.width):
                for y in range(char_img.height):
                    if char_img.getpixel((x, y)) != (255, 255, 255):
                        if left == -1:
                            left = x
                        if x > right:
                            right = x
                        if top == -1 or top > y:
                            top = y
                        if y > bottom:
                            bottom = y

            label.append({
                'left': left,
                'right': right,
                'top': top,
                'bottom': bottom
            })

        with open(os.path.join(output_dir, f'{captcha_text}.json'), 'w') as f:
            json.dump(label, f)
Example #23
0
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_len = random.randint(4, 6)
            random_str = ''.join(
                [random.choice(characters) for j in range(random_str_len)])
            X[i] = generator.generate_image(random_str)
            if random_str_len < n_len:
                for k in range(n_len - random_str_len):
                    random_str += ' '
            for j, ch in enumerate(random_str):
                y[j][i, :] = 0
                y[j][i, characters.find(ch)] = 1

        yield X, y
Example #24
0
    def capImage(self, captcha_text):
        image_captcha = ImageCaptcha()
        # Create the captcha image.
        image = image_captcha.generate_image(captcha_text)

        # Add noise curve for the image.
        image_captcha.create_noise_curve(image, image.getcolors())

        # Add noise dots for the image.
        image_captcha.create_noise_dots(image, image.getcolors())

        # Save the image to a png file.
        image_file = "./captcha_" + captcha_text + ".png"
        image_captcha.write(captcha_text, image_file)

        # Display the image in a matplotlib viewer.
        plt.imshow(image)
        plt.show()
Example #25
0
def gen(batch_size=32):
    X = np.zeros(
        (batch_size, height, width, 3), dtype=np.uint8
    )  # X 的形状是 (batch_size, height, width, 3),比如一批生成32个样本,图片宽度为170,高度为80,那么形状就是 (32, 80, 170, 3),取第一张图就是 X[0]。
    y = [
        np.zeros((batch_size, n_class), dtype=np.uint8) for i in range(n_len)
    ]  # y 的形状是四个 (batch_size, n_class),如果转换成 numpy 的格式,则是 (n_len, batch_size, n_class),比如一批生成32个样本,验证码的字符有36种,长度是4位,那么它的形状就是4个 (32, 36),也可以说是 (4, 32, 36)
    generator = ImageCaptcha(width=width, height=height)
    while True:
        for i in range(batch_size):
            random_str = ''.join(
                [random.choice(characters) for j in range(n_len)])
            img = generator.generate_image(random_str)
            X[i] = img
            for j, ch in enumerate(random_str):
                y[j][i, :] = 0
                y[j][i, characters.find(ch)] = 1
        yield X, y
Example #26
0
async def generate_captcha(user):
    letters = "0123456789abcdefghijklmnopqrstuvwxyz?!()@"
    captcha_answer=''.join(random.choice(letters) for i in range(config.FAUCET_CAPTCHALENGTH))

    image_captcha = ImageCaptcha()

    captcha_image_file_name = os.getcwd()+"\\faucet_images\\"+str(user.id)+"_captcha_image.png"
    image = image_captcha.generate_image(captcha_answer)



    arr=BytesIO()
    image.save(arr, format='png',optimize=True)
    arr.seek(0)

    await user.send(file=discord.File(arr, "captcha.png"))

    return captcha_answer
Example #27
0
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
Example #28
0
def captcha_img(width=160, height=60, font_sizes=(50, 55, 60), fonts=None):

    captcha_len = 5
    #captcha_range = string.digits + string.ascii_letters #大小写+数字
    captcha_range = string.ascii_lowercase
    captcha_range_len = len(captcha_range)
    captcha_text = ""
    for i in range(captcha_len):
        captcha_text += captcha_range[randint(0, captcha_range_len - 1)]

    img = ImageCaptcha(width=width, height=height, font_sizes=font_sizes)
    image = img.generate_image(captcha_text)

    #save to bytes
    bytes_image = BytesIO()
    image.save(bytes_image, format='png')
    bytes_image = bytes_image.getvalue()

    return bytes_image, captcha_text
def gen(batch_size=32):
    '''
    一批的数量:32
    :param batch_size:
    :return:
    '''
    X = np.zeros((batch_size, height, width, 3), dtype=np.uint8)  # 无符号整数64位
    y = [
        np.zeros((batch_size, n_class), dtype=np.uint8) for i in range(n_len)
    ]  # 一个长度为4的列表,每个元素是一个二维张量
    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
Example #30
0
def data_generator(times=100, batch_size=32):
    generator = ImageCaptcha(width=width, height=height)

    for _ in range(times):
        X = np.zeros((batch_size, height, width, 3), dtype=np.uint8)
        XX = np.zeros((batch_size, 3, height, width), dtype=np.uint8)
        y = np.zeros((batch_size, n_len, n_class), dtype=np.uint8)
        yy = np.zeros((batch_size, 4), dtype=np.uint8)
        s = []
        for i in range(batch_size):
            random_str = ''.join(
                [random.choice(characters) for j in range(n_len)])
            X[i] = generator.generate_image(random_str)
            XX[i] = np.transpose(X[i], (2, 0, 1))
            s.append(random_str)
            for j, ch in enumerate(random_str):
                y[i][j][characters.find(ch)] = 1
                yy[i][j] = characters.find(ch)
        yield torch.from_numpy(XX).float(), torch.from_numpy(y).float()
def main(app_args):
    """
        Main application.
    """
    if os.path.exists(app_args.out_path):
        shutil.rmtree(app_args.out_path)
    os.makedirs(app_args.out_path)

    fonts = []
    for file in os.listdir("fonts"):
        if file.endswith(".ttf"):
            fonts.append(os.path.join(app_args.fonts_dir, file))
    image_captcha_gen = ImageCaptcha(fonts=fonts,
                                     height=app_args.image_height,
                                     width=app_args.image_width)

    for i in xrange(app_args.files_count):
        samples = []
        labels = []
        for k in xrange(app_args.file_size):
            captcha_text = random.sample(ALPHABET, app_args.captcha_size)
            data = image_captcha_gen.generate_image(captcha_text)
            captcha = np.array(data)
            captcha = cv2.resize(captcha,
                                 (app_args.image_width, app_args.image_height))
            label = _get_label(captcha_text)
            labels.append(label)
            samples.append(captcha)
            if k % 1000 == 0:
                print("Generated: %d" % k)

        samples = np.array(samples)
        labels = np.array(labels)
        labels = labels.astype(np.int32)

        cur_file_name = "%d_set.hdf5" % i
        cur_hdf5 = h5py.File(os.path.join(app_args.out_path, cur_file_name),
                             "w")
        cur_hdf5.create_dataset("data", data=samples)
        cur_hdf5.create_dataset("labels", data=labels)
        cur_hdf5.close()

        print("Write %s" % cur_file_name)
Example #32
0
def get_randm_image(target_str, random_flag):
    '''
    生成单幅的验证码图片
    :param target_str: 要生成的验证码对应的字符串
    :param random_flag: 是否使用随机模式生成验证码 为True是 target_str参数无效
    :return: 返回验证码图片
    '''
    width, height, n_len, n_class = 170, 80, 4, len(characters)

    generator = ImageCaptcha(width=width, height=height)
    if not random_flag:
        random_str = target_str
    else:
        random_str = ''.join([random.choice(characters) for j in range(n_len)])
    img = generator.generate_image(random_str)

    plt.imshow(img)
    plt.title(random_str)
    plt.show()
    return img
Example #33
0
def main():
    width, height = 170, 80

    generator = ImageCaptcha(width=width, height=height)
    img = generator.generate_image("AAAA")
    img.save("ABCD.png")

    characters = string.digits + string.ascii_uppercase

    #读取model
    model = model_from_json(open('model.json').read())
    model = model.load_weights_from_hdf5_group('model.h5')
    image = cv2.imread("./ABCD.png")

    X = np.zeros((1, height, width, 3), dtype=np.uint8)
    X[0] = image

    y_pred = model.predict(X)
    result = decode(y_pred, characters)
    print(result)
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
Example #35
0
 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')
Example #36
0
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)

        if not result:
            return False
        result = result[2]

        self.app.cache.set(k, None, timeout=10)

        if not self.case_sens:
            solution = solution.lower()
            result = result.lower()

        return solution == result
Example #37
0
# -*-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