Beispiel #1
0
 def captcha_ask(self, error=False, **kwargs):
     """
     helper method to generate a captcha and verify that the user entered the right answer.
     :param error: if True indicates that the previous captcha attempt failed
     :return: a bool indicating if the user entered the right answer or not
     """
     image = ImageCaptcha()
     captcha = j.data.idgenerator.generateXCharID(4)
     # this log is for development purposes so we can use the redis client
     self._log_info("generated captcha:%s" % captcha)
     data = image.generate(captcha)
     self.q_out.put({
         "cat": "captcha_ask",
         "captcha": base64.b64encode(data.read()).decode(),
         "msg": "Are you human?",
         "label": "Please enter a valid captcha" if error else "",
         "kwargs": kwargs,
     })
     return self.q_in.get() == captcha
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)])
            #gen_str = ''.join(random.choice(mix_nb))
            gen_str=''
            gen_char= random.choice(mix_nb)
            if gen_char == '(':
                gen_str += gen_char              #1 '('
                gen_str += random.choice(number) #2 '0-9'
                gen_str += random.choice(sign)   #3 'sign'
                gen_str += random.choice(number) #4 '0-9'
                gen_str += ')'                   #5 ')'
                gen_str += random.choice(sign)   #6 'sign'
                gen_str += random.choice(number) #7 '0-9'
            else:
                gen_str += gen_char              #1 '0-9'
                gen_str += random.choice(sign)   #2 'sign'
                gen_char = random.choice(mix_nb)
                if gen_char == '(':
                    gen_str += gen_char           #3 '('
                    gen_str += random.choice(number) #4 '0-9' 
                    gen_str += random.choice(sign)   #5 'sign'
                    gen_str += random.choice(number) #6 '0-9' 
                    gen_str += ')'                   #7 ')'
                else:
                    gen_str += gen_char              #3 '0-9'
                    gen_str += random.choice(sign)   #4 'sign'
                    gen_str += random.choice(number) #5 '0-9'
                    gen_str += ' '
                    gen_str += ' '

                
            X[i] = imageCap.generate_image(gen_str)
            
            for j, ch in enumerate(gen_str):
                y[j][i, :] = 0
                y[j][i, characters.find(ch)] = 1
        yield X, y
Beispiel #3
0
def gen_captcha_text_and_image():

    while (1):
        image = ImageCaptcha(180, 67)
        # image = ImageCaptcha()

        captcha_text = random_captcha_text()
        captcha_text = ''.join(captcha_text)
        path = 'F://CNN_1/test/'
        print("-----------------" + captcha_text)
        captcha = image.generate(captcha_text)
        # image.write(captcha_text, path+captcha_text + '.jpg')  # 写到文件

        captcha_image = Image.open(captcha)
        #captcha_image.show()
        captcha_image = np.array(captcha_image)
        if captcha_image.shape == (67, 180, 3):
            break

    return captcha_text, captcha_image
Beispiel #4
0
def create_image_captcha(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"
    imgByteArr = BytesIO()
    image.save(imgByteArr, format='PNG')
    imgByteArr = imgByteArr.getvalue()
    open("test.png", "wb").write(imgByteArr)
    #image_captcha.write(captcha_text, image_file)

    print(image_file + " has been created.")
Beispiel #5
0
def generate_captcha_images(captchaImgPath,
                            total,
                            charSet=CHAR_SET,
                            charSetLen=CHAR_SET_LEN):
    k = 0
    captcha_text = ""
    for i in range(CHAR_SET_LEN):
        for j in range(CHAR_SET_LEN):
            for m in range(CHAR_SET_LEN):
                for n in range(CHAR_SET_LEN):
                    captcha_text = charSet[i] + charSet[j] + charSet[
                        m] + charSet[n]
                    if os.path.exists(captchaImgPath + captcha_text + '.jpg'):
                        continue
                    image = ImageCaptcha()
                    image.write(captcha_text,
                                captchaImgPath + captcha_text + '.jpg')
    k += 1
    if k >= total:
        return
def generate_captcha_image(charSet=char_set,
                           charSetLen=char_set_len,
                           captchaImagePath=captcha_image_path):

    captcha_text = ''
    for i in range(captcha_len):
        c = random.choice(char_set)
        captcha_text += c
    print(captcha_text)
    image = ImageCaptcha()
    #生成并显示验证码
    # img = image.generate(captcha_text)
    # captcha_image = Image.open(img)
    # captcha_image = np.array(captcha_image)
    # plt.imshow(captcha_image)
    # plt.show()

    if not os.path.exists(captchaImagePath):
        os.mkdir(captchaImagePath)
    image.write(captcha_text, captchaImagePath + "/" + captcha_text + ".png")
Beispiel #7
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
Beispiel #8
0
def create_captcha_dataset(size=100,
                           data_dir='D:\\验证码数据集\\data\\',
                           height=60,
                           width=60,
                           image_format='.png'):
    """ 创建并保存验证码数据集的到文件中 """
    tf.io.gfile.makedirs(data_dir)
    captcha = ImageCaptcha(width=width, height=height)  # 创建ImageCaptcha实例
    count = 0
    for _ in range(size):
        count += 1
        i = str(count)
        image_format = '_' + str(count) + '.jpg'
        # 随机生成验证码字符串
        text = gen_random_text(CAPTCHA_CHARSET, CAPTCHA_LEN)
        captcha.write(
            text, data_dir + text +
            image_format)  # 注意相同的验证码图片会overwrite,所有实际上图片会比5000和1000要少
    print('生成了验证图片:', count)
    return None
    def __init__(self, vocab=string.digits):

        self._base_dir_name = "generated_images_{dt}".format(
            dt=datetime.datetime.now().strftime("%s"))

        # Create the base dir we're gonna save our generated images in
        os.mkdir(self._base_dir_name)

        self.font = "/Users/tomtalpir/dev/tom/captcha_project/CaptchaImgGeneration/fonts/Seravek.ttc"
        self.img_w = 200
        self.img_h = 200

        self.captcha_generator = ImageCaptcha(width=self.img_w,
                                              height=self.img_h,
                                              fonts=[self.font])
        self.vocab = string.ascii_lowercase + string.digits
        # self.vocab = string.ascii_lowercase

        self.n_min_chars = 5
        self.n_max_chars = 10
Beispiel #10
0
def gen_captcha_text_and_image(width=CAPTCHA_WIDTH,
                               height=CAPTCHA_HEIGHT,
                               save=None):
    '''
    生成随机验证码
    :param width:
    :param height:
    :param save:
    :return: np数组
    '''
    image = ImageCaptcha(width=width, height=height)
    # 验证码文本
    captcha_text = random_captcha_text()
    captcha = image.generate(captcha_text)
    # 保存
    if save: image.write(captcha_text, captcha_text + '.jpg')
    captcha_image = Image.open(captcha)
    # 转化为np数组
    captcha_image = np.array(captcha_image)
    return captcha_text, captcha_image
Beispiel #11
0
def gen_captcha_text_and_image():
    # 验证码生成类
    image = ImageCaptcha()

    # 获取验证码文字
    captcha_text = random_captcha_text()
    # List转化为字符串
    captcha_text = ''.join(captcha_text)

    # 生成图片
    captcha = image.generate(captcha_text)

    # 保存到磁盘
    image.write(captcha_text, captcha_text + '.jpg')

    captcha_image = Image.open(captcha)
    # 转化为np.array(供Tensorflow识别)
    captcha_image = np.array(captcha_image)
    # 返回label,和图片
    return captcha_text, captcha_image
Beispiel #12
0
def create_image_captcha(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()

    print(image_file + " has been created.")
Beispiel #13
0
    async def captcha_example(self, ctx):
        image = ImageCaptcha(fonts=['Others/font1.ttf', 'Others/font2.ttf'])

        data = image.generate("1234")

        image.write("1234", 'CaptchaExample.png')

        embed = discord.Embed(
            title = "Example of an Captcha",
            color = ctx.author.color,
            timestamp = ctx.message.created_at
        )
        files = discord.File("CaptchaExample.png")
        embed.set_image(
            url = "attachment://CaptchaExample.png"
        )
        embed.set_footer(
            text = "Note that Captchas are generated with different numbers and characters. This is only an example of a single captcha with the answer \"1234\"!"
        )
        await ctx.send(embed=embed, file=files)
Beispiel #14
0
def generate_captcha_image(charSet=CHAR_SET,
                           charSetLen=CHAR_SET_LEN,
                           captchaImgPath=CAPTCHA_IMAGE_PATH):
    k = 0
    total = 1
    for i in range(CAPTCHA_LEN):
        total *= charSetLen

    for i in range(charSetLen):
        for j in range(charSetLen):
            for m in range(charSetLen):
                for n in range(charSetLen):
                    captcha_text = charSet[i] + charSet[j] + charSet[
                        m] + charSet[n]
                    image = ImageCaptcha()
                    image.write(captcha_text,
                                captchaImgPath + captcha_text + '.jpg')
                    k += 1
                    sys.stdout.write("\rCreating %d/%d" % (k, total))
                    sys.stdout.flush()
 def __init__(self):
     root = Tk()
     root.title("Captcha Verification")
     self.actual = str(random.randint(1, 100)) + self.randOps() + str(random.randint(1, 100))
     print(self.actual) #For generating random string of mathmatical expression
     Label(root, text = "Math based Captcha Verification",font = "comicsansms 19 bold").pack()
     image = ImageCaptcha(fonts = ['captcha.ttf']) #Font for captcha
     data = image.generate(self.actual) 
     image.write(self.actual, "out.png") #Output image of captcha
     img = Image.open("out.png")
     w,h = img.size
     img = img.resize((w*4,h*3))
     img.save("out.png")
     photo = ImageTk.PhotoImage(img)
     Label(root, text = "Submit", image = photo).pack() #Putting image of captcha in tkinter 
     Label(root, text = "Enter the captcha:", font = "comicsansms 12 bold").pack()
     self.captchaInput = Entry(root)
     self.captchaInput.pack()
     Button(root, text = "Submit", command=self.submit).pack()
     root.mainloop()
Beispiel #16
0
def generate_captcha_image(charSet=CHAR_SET,
                           charSetLen=CHAR_SET_LEN,
                           captchaImgPath=CAPTCHA_IMAGE_PATH):
    k = 0
    list = []
    for i in range(15001):
        captcha_text = ''

        for i in range(4):
            captcha_text += charSet[random.randint(0, 61)]
        temp_captcha = captcha_text.upper()
        if temp_captcha not in list:
            list.append(temp_captcha)
            #  fonts = ['./simsun.ttc'],可以加载字体文件生成不同字体的验证码
            #     image = ImageCaptcha(fonts = ['./simsun.ttc'],width=180,height=60)
            image = ImageCaptcha(width=120, height=40)
            image.write(captcha_text, captchaImgPath + captcha_text + '.jpg')
            k += 1
        else:
            continue
def gen_verifycode_pic():
    # 指定大小 180 * 67
    img = ImageCaptcha(180, 67)
    # 指定文本,长度4位
    txt = gen_verifycode_txt()
    txt = ''.join(txt)
    # 测试,打印出验证码文本
    # print('-------------- ' + txt)
    # 根据文本生成图像
    captcha = img.generate(txt)
    # 写入文件
    img.write(txt, PIC_DIR + txt + EXT)
    captcha_image = Image.open(captcha)

    # 图片显示出来
    # captcha_image.show()
    captcha_image = np.array(captcha_image)

    # 返回最终图形对象和文字
    return txt, captcha_image
def generateCaptchaTextAndImage(width=CAPTCHA_WIDTH,
                                height=CAPTCHA_HEIGHT,
                                save=False):
    """
    生成随机验证码
    :param width: 验证码图片宽度
    :param height: 验证码图片高度
    :param save: 是否保存(None)
    :return: 验证码字符串,验证码图像np数组
    """
    image = ImageCaptcha(width=width, height=height)
    # 验证码文本
    captchaText = randomCaptchaText(char_set=CAPTCHA_LIST,
                                    captcha_size=CAPTCHA_LENGTH)
    captcha = image.generate(captchaText)

    captcha_image = Image.open(captcha)
    # 转化为np数组
    captcha_image = np.array(captcha_image)
    return captchaText, captcha_image
Beispiel #19
0
def generate_train_image(char_set=CHAR_SET, char_set_len=CHAR_SET_LEN, captcha_image_path=CAPTCHA_IMAGE_PATH):
    cnt = 0
    num_of_image = 1
    image = ImageCaptcha()
    for i in range(CAPTCHA_LEN):
        num_of_image *= char_set_len

    if not os.path.exists(captcha_image_path):
        os.mkdir(captcha_image_path)

    for i in range(char_set_len):
        for j in range(char_set_len):
            for k in range(char_set_len):
                for l in range(char_set_len):
                    image_context = char_set[i] + char_set[j] + char_set[k] + char_set[l]
                    image.write(image_context, os.path.join(captcha_image_path, image_context+'.jpg'))

                    cnt += 1
                    sys.stdout.write('Created (%d %d)' % (cnt, num_of_image))
                    sys.stdout.flush()
Beispiel #20
0
def gen_cnn(batch_size=5):

    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, font_sizes=[25])
    while True:
        for i in range(batch_size):
            word = choice(english_words)
            word_len = len(word)
            x[i] = np.array(generator.generate_image(word))
            for j, ch in enumerate(word):
                y[j][i, :] = 0
                y[j][i, characters.find(ch)] = 1

            if len(word) < N_LEN:
                for k in range(word_len, N_LEN):
                    y[k][i, :] = 0
                    y[k][i, characters.find("#")] = 1

        yield x, y
Beispiel #21
0
def verifyCode(request):
    # 初始化画布,初始化画笔
    from captcha.image import ImageCaptcha
    from random import randint
    list = [
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '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', '', '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'
    ]
    chars = ''
    for i in range(4):
        chars += list[randint(0, 61)]
    image = ImageCaptcha().generate_image(chars)

    fp = BytesIO()
    image.save(fp, "png")
    request.session['code'] = chars
    return HttpResponse(fp.getvalue(), content_type="image/jpeg")
Beispiel #22
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)
Beispiel #23
0
def generate_image_sets_for_single_digit(nb_sample=SAMPLE_SIZE,
                                         single_digit_index=0):
    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 = list()

    for digit_index in range(0, DIGIT_COUNT):
        digit_labels.append(np.empty(nb_sample, 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[digit_index][index] = labels[index][digit_index]

    x = digit_image_data
    y = to_categorical(digit_labels[single_digit_index], CLASS_COUNT)

    return x, y
Beispiel #24
0
def captcha_img(width=320,
                height=120,
                font_sizes=(100, 110, 120, 200, 210, 220),
                fonts=None):

    captcha_len = 5
    captcha_range = string.digits + string.ascii_letters
    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
Beispiel #25
0
def gen_captcha_text_and_image(width=CAPTCHA_WIDTH,
                               height=CAPTCHA_HEIGHT,
                               save=None):
    """
    生成随机验证码
    :param width: 验证码图片宽度
    :param height: 验证码图片高度
    :param save: 是否保存(None)
    :return: 验证码字符串,验证码图像np数组
    """
    image = ImageCaptcha(width=width, height=height)
    # 验证码文本
    captcha_text = random_captcha_text()
    captcha = image.generate(captcha_text)
    # 保存
    if save:
        image.write(captcha_text, './img/' + captcha_text + '.jpg')
    captcha_image = Image.open(captcha)
    # 转化为np数组
    captcha_image = np.array(captcha_image)
    return captcha_text, captcha_image
def gen_captcha_text_and_image(i):
    image = ImageCaptcha(width=width_p,
                         height=height_p,
                         font_sizes=[90, 100, 110])

    captcha_text = random_captcha_text()
    captcha_text = ''.join(captcha_text)

    path = './generated/'
    if os.path.exists(
            path) == False:  # if the folder is not existed, create it
        os.mkdir(path)

    captcha = image.generate(captcha_text)

    # naming rules: num(in order)+'_'+'captcha text'.include num is for avoiding the same name
    image.write(captcha_text, path + captcha_text + '.png')

    captcha_image = Image.open(captcha)
    captcha_image = np.array(captcha_image)
    return captcha_text, captcha_image
Beispiel #27
0
def get_captcha(width=64, height=64, text='a', color=False):
    # Generate captcha.
    image = ImageCaptcha(width, height)
    captcha = image.generate_image(text)

    # Preprocess it into a greyscale numpy array.
    final = captcha
    data = None
    if not color:
        final = final.convert('L')
        (width, height) = final.size
        data = list(final.getdata())
        data = np.array(data)
        data = data.reshape((width, height))
    else:
        final = final.convert('RGB')
        data = list(final.getdata())
        data = np.array(data)
        data = data.reshape((width, height, 3))

    return data, text
Beispiel #28
0
def gen_pic(batch_size=32):
    global conv_shape
    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,
                             font_sizes=[25])

    while True:
        for i in range(batch_size):
            word = choice(english_words)
            word_len = len(word)
            X[i] = np.array(generator.generate_image(word)).transpose(1, 0, 2)
            for j, ch in enumerate(word):
                y[i][j] = characters.find(ch)

            if len(word) < N_LEN:
                for k in range(word_len, N_LEN):
                    y[i][k] = (characters.find("#"))

        yield [np.array(X), np.array(y), np.ones(batch_size)*int(conv_shape[1]-2),
               np.ones(batch_size)*N_LEN], np.ones(batch_size)
Beispiel #29
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-p",
                        "--path",
                        required=False,
                        help="path to store generated images")
    parser.add_argument("-n",
                        "--number",
                        required=True,
                        help="number of images generated")
    producer = ImageCaptcha(width=128,
                            height=64,
                            font_sizes=[40])
    args = vars(parser.parse_args())
    if "path" not in args:
        path = ""
    else:
        path = args['path']
    for i in range(int(args['number'])):
        number_to_write = "".join([random.choice(string.digits) for _ in range(4)])
        producer.write(number_to_write, os.path.join(path, str(i)+"_"+number_to_write+".png"))
Beispiel #30
0
def gen_capthcha_text_and_image(m):
    """
    生成验证码图片
    :param m: 验证码序号
    :return: none
    """
    image = ImageCaptcha()
    # 获取写入字符串
    captcha_text = random_captcha_text()
    captcha_text = ' '.join(captcha_text)
    captcha = image.generate(captcha_text)

    captcha_image = Image.open(captcha)
    captcha_image = np.array(captcha_image)
    # 写入标签
    with open(data_path + "label.txt", "a") as f:
        f.write(captcha_text)
        f.writelines("\n")
    # 写入图片
    name = data_path + 'src/' + '{0:0>4}'.format(m) + '.jpg'
    cv2.imwrite(name, captcha_image)