def main():
        parser = argparse.ArgumentParser()
        parser.add_argument("font_path", help="Path to ttf font file")
        parser.add_argument("output", help="Output filename including extension (e.g. 'sample.jpg')")
        parser.add_argument("--num", help="Up to 4 digit number [Default: random]")
        args = parser.parse_args()

        captcha = ImageCaptcha(fonts=[args.font_path])
        captcha_str = args.num if args.num else DigitCaptcha.get_rand(3, 4)
        img = captcha.generate(captcha_str)
        img = np.fromstring(img.getvalue(), dtype='uint8')
        img = cv2.imdecode(img, cv2.IMREAD_GRAYSCALE)
        cv2.imwrite(args.output, img)
        print("Captcha image with digits {} written to {}".format([int(c) for c in captcha_str], args.output))
Beispiel #2
0
def do_image():
    # image = ImageCaptcha(fonts=['./comic.ttf', './comicbd.ttf'])
    image = ImageCaptcha(width=100, height=50)

    # data = image.generate('1234')
    # assert isinstance(data, BytesIO)
    image.write('1234', 'out.%s' % fmt_suffix.get(fmt, fmt), fmt=fmt)
Beispiel #3
0
 def getCaptcha(self):
     _chars = 'ABCDEFGHJKLMNPQRSTUVWXY23456789'
     chars = random.sample(_chars, 4)
     self.session.captcha = (''.join(chars)).lower()
     image = ImageCaptcha(fonts=['./static/fonts/arial.ttf', './static/fonts/arial.ttf'])
     data = image.generate(chars)
     return data
Beispiel #4
0
def do_image():
    # image = ImageCaptcha(fonts=['./comic.ttf', './comicbd.ttf'])
    image = ImageCaptcha()

    # data = image.generate('1234')
    # assert isinstance(data, BytesIO)
    image.write("1234", "out.jpeg", format="jpeg")
Beispiel #5
0
    def on_get(self, req, resp):
        # Generate a new captcha

        image = ImageCaptcha(fonts = ['fonts/UbuntuMono-R.ttf'])

        captcha_uuid = str(uuid.uuid4())
        captcha_answer = ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for _ in range(6))
        captcha_image = 'data:image/png;base64,' + str(base64.b64encode(image.generate(captcha_answer).getvalue())).split("'")[1]

        # The answer should be case insensitive, the caps are just there for the bots
        captcha_answer = captcha_answer.lower()

        captcha = db.Captcha(
            uuid = captcha_uuid,
            answer_hash = nacl.hash.sha256(str.encode(captcha_uuid + captcha_answer), encoder = nacl.encoding.RawEncoder),
            ip_address_hash = nacl.hash.sha256(str.encode(captcha_uuid + req.remote_addr), encoder = nacl.encoding.RawEncoder),
            user_agent_hash = nacl.hash.sha256(str.encode(captcha_uuid + req.user_agent), encoder = nacl.encoding.RawEncoder)
        )

        db_session = req.context['db_session']

        db_session.add(captcha)
        db_session.commit()

        resp.status = falcon.HTTP_200
        resp.body = json.dumps({
            'uuid': captcha_uuid,
            'image': captcha_image
        })
Beispiel #6
0
 def stress_image(i):
     image = ImageCaptcha(width=100, height=50, fonts=['./Mirvoshar.ttf'], font_sizes=[50, 54, 57, 64])
     d = str(i)
     if os.path.exists(d):
         shutil.rmtree(d)
     os.makedirs(d)
     for t in texts:
         image.write(t, os.path.join(d, '%s.%s' % (t, fmt_suffix.get(fmt, fmt))), fmt=fmt)
Beispiel #7
0
    def test_image_generate():
        captcha = ImageCaptcha()
        data = captcha.generate('1234')
        assert hasattr(data, 'read')

        captcha = WheezyCaptcha()
        data = captcha.generate('1234')
        assert hasattr(data, 'read')
Beispiel #8
0
def gen_captcha_base64(length=None):
    length = length if length else LENGTH
    image = ImageCaptcha(width=130, height=60)  # fonts=FONTS)
    text = random_text(length).lower()
    im = image.generate(text)
    code_signature = sign(text)
    b64 = base64.b64encode(im.getvalue()).decode("utf-8")
    return f"data:image/png;base64, {b64}", code_signature
Beispiel #9
0
def gen_captcha(length=None):
    length = length if length else LENGTH
    image = ImageCaptcha(width=130, height=60)  # fonts=FONTS)
    text = random_text(length)
    image.generate(text)
    code_signature = sign(text)
    fpath = os.path.join(OUTDIR, code_signature + ".png")
    image.write(text, fpath)
    return fpath, code_signature
def gen_captcha_text_and_image():
    image = ImageCaptcha()
    #获得随机生成的验证码
    captcha_text = random_captcha_text()
    #把验证码列表转为字符串
    captcha_text = ''.join(captcha_text)
    #生成验证码
    captcha = image.generate(captcha_text)
    image.write(captcha_text, 'captcha/images/' + captcha_text + '.jpg')  # 写到文件
Beispiel #11
0
def gen_captcha_image_random():
    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)
    print(captcha_image)
Beispiel #12
0
def gen_captcha_text_and_image():
	image = ImageCaptcha()
 
	captcha_text = random_captcha_text()
	captcha_text = ''.join(captcha_text)
 
	captcha = image.generate(captcha_text)
	#image.write(captcha_text, captcha_text + '.jpg')  # 写到文件
 
	captcha_image = Image.open(captcha)
	captcha_image = np.array(captcha_image)
	return captcha_text, captcha_image
Beispiel #13
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
Beispiel #14
0
def generate_verification_code(request):
    '''
    '''

    code = random_code_generator(5)
    image = ImageCaptcha()
    image.write(code, 'captcha/{0}.png'.format(code))
    verification_code = { 'verification_image': '{0}.png'.format(code),
                            'code': code}

    return HttpResponse(json.dumps(verification_code),
                        status=200,
                        content_type='application/json')
Beispiel #15
0
def gen_captcha_text_and_image():
	image = ImageCaptcha()

	# captcha_text = random_captcha_text()#使用带有字母和数字的随机组合
	captcha_text = random_captcha_num()#使用只有数字的随机组合
	captcha_text = ''.join(captcha_text)

	captcha = image.generate(captcha_text)
	# image.write(captcha_text, save_file+captcha_text + '.jpg')  # 写到文件

	captcha_image = Image.open(captcha)
	captcha_image = np.array(captcha_image)
	return captcha_text, captcha_image
Beispiel #16
0
def request_img(request):
    captcha_id = request.params['id']
    if not captcha_id:
        return HTTPNotFound('Not Found Resource')
    with transaction.manager:
        captcha = DBSession.query(CaptchaCode).get(captcha_id)
        if not captcha:
            return HTTPNotFound('Not Found Resource')

        image = ImageCaptcha(fonts=[ttf_path], font_sizes=(48, 49, 50), width=130)
        image_data = image.generate(captcha.code)
        response = Response(image_data.read())
        response.content_type = "image/jpeg"
        return response
Beispiel #17
0
def myCaptchaLoader(request):
	to_json_response = dict()
	image = None
	try:
		print "IN CAPTCHA METHOD....."
            	to_json_response['status'] = 1
		image = ImageCaptcha(fonts=['Ubuntu-B.ttf', 'UbuntuMono-R.ttf'])
		
		image.write('1234','out.png')	
		print "CAPTCHA CREATED..."	
	except:	
		print "\nException OCCURED",sys.exc_info()[0]

	return StreamingHttpResponse(json.dumps(to_json_response),content_type="application/json")
Beispiel #18
0
    def appear(self):
        # Make captcha
        row = str(uuid.uuid4())[:4]
        img = ImageCaptcha()
        data = img.generate("1")
        assert isinstance(data, BytesIO)
        img.write(row, "captcha.png")
        pixmap = QtGui.QPixmap("captcha.png")
        self.ui.captcha_lb.setPixmap(pixmap)
        os.remove("captcha.png")

        # Appear win
        self.show()
        self.animation_appear.start()
Beispiel #19
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
Beispiel #20
0
def newcaptcha(text, fontspath='captcha/fonts/'):
    cherrypy.session['capt_code'] = text
    fonts = []
    for x in os.listdir(fontspath):
        if x.split('.')[-1] == 'ttf':#if font file
            fonts.append(fontspath+x)
                     
    img = StringIO.StringIO()
    
    image = ImageCaptcha(fonts=fonts)
    data = image.generate(text)
    image.write(text, img)

    contents = img.getvalue()
    img.close()

    return contents
def add_to_form_context(context):
    config = pluginapi.get_config('mediagoblin.plugins.lepturecaptcha')
    captcha_secret = config.get('CAPTCHA_SECRET_PHRASE')
    captcha_charset = config.get('CAPTCHA_CHARACTER_SET')
    captcha_length = config.get('CAPTCHA_LENGTH')

    captcha_string = u''.join([choice(captcha_charset) for n in xrange(captcha_length)])

    captcha_hash = sha1(captcha_secret + captcha_string).hexdigest()
    context['captcha_hash'] = captcha_hash

    image = ImageCaptcha()
    data = image.generate(captcha_string)
    captcha_image = base64.b64encode(data.getvalue())
    context['captcha_image'] = captcha_image

    return context
Beispiel #22
0
def gen_captcha_text_and_image():
    while (1):
        image = ImageCaptcha()

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

        captcha = image.generate(captcha_text)
        # image.write(captcha_text, captcha_text + '.jpg')  # 写到文件

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

    return captcha_text, captcha_image
Beispiel #23
0
def gen_captcha_text_and_image():
    size = random.randint(4, 20)
    image = ImageCaptcha(height=128, width=(size * 40 + 40), font_sizes=(80, 90, 100, 112))
    captcha_text = random_captcha_text(captcha_size=size)
    captcha_text = ''.join(captcha_text)

    captcha = image.generate(captcha_text)
    # image.write(captcha_text, captcha_text + '.jpg')  # 写到文件

    captcha_image = Image.open(captcha)
    w, h = captcha_image.size
    captcha_image = captcha_image.resize((w // 4, h // 4))

    captcha_image.save('train_data/' + captcha_text + '.jpg', 'jpeg')  # 写到文件

    # 调试用显示
    # captcha_image = np.array(captcha_image)
    return captcha_text, captcha_image
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
Beispiel #25
0
def gen_captcha_text_and_image():
    image = ImageCaptcha()
    # plt.imshow(image)
    # plt.show()

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

    captcha = image.generate(captcha_text)
    #print(captcha)
    #image.write(captcha_text, captcha_text + '.jpg')  # 写到文件

    captcha_image = Image.open(captcha)
    #print(captcha_image)
    captcha_image = np.array(captcha_image)
    #print(captcha_image)

    return captcha_text, captcha_image
Beispiel #26
0
def generate_code_image(code_size=4):
    """
    产生一个验证码的Image对象
    :param code_size:
    :return:
    """
    image = ImageCaptcha()
    code_text = random_code_text(code_size)
    code_text = ''.join(code_text)
    # 将字符串转换为验证码(流)
    captcha = image.generate(code_text)
    # 如果要保存验证码图片
    image.write(code_text, 'captcha/' + code_text + '.jpg')

    # 将验证码转换为图片的形式
    code_image = Image.open(captcha)
    code_image = np.array(code_image)

    return code_text, code_image
 def __init__(self, characters, batch_size, steps, width=160, height=60):
     # 字符集
     self.characters = characters
     # 批次大小
     self.batch_size = batch_size
     # 生成器生成多少个批次的数据
     self.steps = steps
     # 验证码长度随机,3-6位
     self.n_len = np.random.randint(3, 7)
     # 验证码图片宽度
     self.width = width
     # 验证码图片高度
     self.height = height
     # 字符集长度
     self.num_classes = num_classes
     # 用于产生验证码图片
     self.image = ImageCaptcha(width=self.width, height=self.height)
     # 用于保存最近一个批次验证码字符
     self.captcha_list = []
Beispiel #28
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()
Beispiel #29
0
def gen_captcha_text_and_image(i):
    image = ImageCaptcha(width=160, height=60, font_sizes=[30])

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

    path = './data/'
    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 + str(i) + '_' + captcha_text + '.png')

    captcha_image = Image.open(captcha)
    captcha_image = np.array(captcha_image)
    return captcha_text, captcha_image
Beispiel #30
0
def gen_captcha_text_and_image(num=1):
    """generate captcha image randomly
    Arguments:
        num -- integer, specify the number of \
            images to be generated, default 1
    Return:
        texts -- np.array with shape (num, captcha_size)
        images -- np.array with shape (num, 60, 160, 3)
    """
    image = ImageCaptcha()

    captcha_texts = random_captcha_text(num=num)
    captcha_images = []
    for i in range(num):
        captcha = image.generate(captcha_texts[i])
        captcha_image = Image.open(captcha)
        captcha_image = np.array(captcha_image)
        captcha_images.append(captcha_image)
    return captcha_texts, np.array(captcha_images)
Beispiel #31
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):
    '''
    一批的数量: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
    def __init__(self, count, batch_size, num_label, height, width):
        super(OCRIter, self).__init__()
        self.captcha = ImageCaptcha(fonts=['./data/Xerox.ttf'])

        self.batch_size = batch_size
        self.count = count
        self.height = height
        self.width = width
        self.provide_data = [('data', (batch_size, 3, height, width))]
        self.provide_label = [('softmax_label', (self.batch_size, num_label))]
Beispiel #34
0
def manage_captcha():
    global global_captchas
    global allowed_posters
    if request.method == 'POST':
        if request.form['captchanum'] and request.form['answer']:
            #these next two lines are nasty, maybe use a varible? MAKE A F*****G VARIBLE
            if int(request.form['captchanum']) <= len(global_captchas):
                if global_captchas[int(request.form['captchanum']) -
                                   1].isActive() and global_captchas[
                                       int(request.form['captchanum']) -
                                       1].checkAnswer(request.form['answer']):
                    allowed_posters.append(request.remote_addr)
                    #print(str(request.remote_addr) + ' added to allowed_posters')
                    #remove the file from the array of active captchas and delete the file.
                    global_captchas.remove(
                        global_captchas[int(request.form['captchanum']) - 1])
                    os.remove('static/' +
                              str(int(request.form['captchanum']) - 1) +
                              '.png')
                    return "Success, you may now go back and post"
                else:
                    return "there was an error, please try again"
            else:
                return "there was an error with the captcha, please try again " + str(
                    request.form['captchanum']) + " " + str(
                        len(global_captchas))
    elif request.method == 'GET':
        random = str(randint(1000, 9999))
        image = ImageCaptcha(fonts=[
            '/usr/share/fonts/TTF/DejaVuSans.ttf',
            '/usr/share/fonts/TTF/DejaVuSerif.ttf'
        ])
        data = image.generate(random)
        #assert isinstance(data, BytesIO)
        #ok maybe making this filename is inefficent
        name = str(len(global_captchas) + 1)
        #put the new file in the templates folder so the template can use it (i feel like this is bad)
        image.write(random, 'static/' + name + '.png')
        global_captchas.append(Captcha('static/' + name + '.png', random))
        #return send_file(str(len(global_captchas)) + '.png')
        return render_template('captcha.html', name=str(len(global_captchas)))
    else:
        return "WUT U DID SOMETHING WRONG"
def gen(gen_dir, nb_sample, fonts, font_sizes):
    if not os.path.exists(gen_dir):
        os.makedirs(gen_dir)
    image = ImageCaptcha(width=IMAGE_WIDTH,
                         height=IMAGE_HEIGHT,
                         font_sizes=font_sizes,
                         fonts=fonts)

    print("Creating dataset for {}".format(gen_dir.split('/')[-1]))
    f = open(gen_dir + ".csv", "w")
    f.write("ImageId,Label\n")
    for i in tqdm(range(nb_sample)):
        label = ''
        for j in range(CHAR_NUM):
            label += random.choice(CHAR_SETS)
        fname = binascii.hexlify(os.urandom(16)).decode('ascii') + '.png'
        image.write(label, os.path.join(gen_dir, fname))
        f.write("{},{}\n".format(fname, label))
    f.close()
Beispiel #36
0
def Verification_code_generation():
    ver_data = ''.join(random.sample(string.ascii_lowercase + string.digits,
                                     4))
    captcha_image = Image.open(ImageCaptcha().generate(ver_data))
    path = './captcha_image'
    if not os.path.exists(path):
        os.makedirs(path)
    filename = ver_data + '.png'
    captcha_image.save(path + os.path.sep + filename)
    return ver_data
Beispiel #37
0
    def gen_captcha_text_and_image(self):
        image = ImageCaptcha()

        captcha_text, vec = self.random_text()
        captcha_text = ''.join(captcha_text)
        #print(captcha_text)

        captcha = image.generate(captcha_text)
        # image.write(captcha_text, captcha_text + '.jpg')  # 写到文件

        captcha_image = Image.open(captcha)
        captcha_image = np.array(captcha_image)
        #captcha_image = self.convert2gray(captcha_image)
        gray_image = cv2.cvtColor(captcha_image, cv2.COLOR_RGB2GRAY)
        _, image_bi = cv2.threshold(gray_image, 195, 255, cv2.THRESH_BINARY)
        #_,contours,_ = cv2.findContours(image_bi,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
        #image_no_noise = self.no_noise(image_bi,contours,100.0)
        image_medianblur = cv2.medianBlur(image_bi, 5)
        return image_medianblur, captcha_text, vec
Beispiel #38
0
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()
    captcha = image.generate(captchaText)

    captcha_image = Image.open(captcha)
    # 转化为np数组
    captcha_image = np.array(captcha_image)
    return captchaText, captcha_image
Beispiel #39
0
 def __init__(self, count, batch_size, num_label, init_states):
     super(OCRIter, self).__init__()
     self.captcha = ImageCaptcha(fonts=['./data/Xerox.ttf'])
     self.batch_size = batch_size
     self.count = count
     self.num_label = num_label
     self.init_states = init_states
     self.init_state_arrays = [mx.nd.zeros(x[1]) for x in init_states]
     self.provide_data = [('data', (batch_size, 2400))] + init_states
     self.provide_label = [('label', (self.batch_size, 4))]
Beispiel #40
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
Beispiel #41
0
def getTraindata():
    image = ImageCaptcha(width=CaptchaAttr['imgWidth'],
                         height=CaptchaAttr['imgHeight'])
    s = "".join([
        random.choice(num + UPPERCASE + lowercase)
        for len in range(CaptchaAttr['geneLen'])
    ])
    data = image.generate(s)

    # print(data)
    #按灰度读入
    # arr = np.array(Image.open(data).convert('L')).flatten() / 255;
    arr1 = np.array(Image.open(data))
    arr = np.array(Image.open(data).convert('L'))

    # plt.imsave("./img/Train/"+s+".png", arr1);
    # image.write(s, "./img/Train/"+s+'.png')
    # print(arr.shape)
    return arr, s, arr1
Beispiel #42
0
def gen_captcha_text_and_image(char_set=number + alphabet + ALPHABET,
                               captcha_size=4,
                               width=160,
                               height=80,
                               saveToFile=None):
    image = ImageCaptcha(width=width, height=height)

    captcha_text = random.sample(list(char_set), captcha_size)
    captcha_text = ''.join(captcha_text)

    captcha = image.generate(captcha_text)

    if saveToFile != None:
        image.write(captcha_text, saveToFile)  # 写到文件

    captcha_image = Image.open(captcha)
    #输出就是图片的矢量
    captcha_image = np.array(captcha_image)
    return captcha_text, captcha_image
Beispiel #43
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 #44
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 #45
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
Beispiel #46
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 #47
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 #48
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 #49
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)
 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 #51
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
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
Beispiel #53
0
    def __init__(self, count, batch_size, num_label, height, width):
        super(OCRIter, self).__init__()
        list = VG.getFont()
        self.captcha = ImageCaptcha(fonts=['C:/Windows/Fonts/' + list[0]])

        self.batch_size = batch_size
        self.count = count
        self.height = height
        self.width = width
        self.provide_data = [('data', (batch_size, 3, height, width))]
        self.provide_label = [('softmax_label', (self.batch_size, num_label))]
Beispiel #54
0
 def __init__(self, count, batch_size, num_label, init_states):
     super(OCRIter, self).__init__()
     # you can get this font from http://font.ubuntu.com/
     self.captcha = ImageCaptcha(fonts=['./font/Ubuntu-M.ttf'])
     self.batch_size = batch_size
     self.count = count
     self.num_label = num_label
     self.init_states = init_states
     self.init_state_arrays = [mx.nd.zeros(x[1]) for x in init_states]
     self.provide_data = [('data', (batch_size, 2400))] + init_states
     self.provide_label = [('label', (self.batch_size, 4))]
Beispiel #55
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 #56
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()
Beispiel #57
0
 def __init__(self, h, w, font_paths):
     """
     Parameters
     ----------
     h: int
         Height of the generated images
     w: int
         Width of the generated images
     font_paths: list of str
         List of all fonts in ttf format
     """
     self.captcha = ImageCaptcha(fonts=font_paths)
     self.h = h
     self.w = w
Beispiel #58
0
def gen_captcha_text_and_image():
    image = ImageCaptcha()

    # 此处只训练只有小写字母的结果
    captcha_text = random_captcha_text()
    captcha_text = ''.join(captcha_text)

    captcha = image.generate(captcha_text)

    # # 存储文件使用
    # base_dir = os.path.abspath(os.path.dirname(__file__))
    # files_dir = os.path.abspath(os.path.join(os.getcwd(), '../static'))
    # print(files_dir)
    # image_dir = os.path.join(files_dir, 'captcha.jpg')
    #
    # image.write(captcha_text, image_dir)

    # 生成训练文件
    captcha_image = Image.open(captcha)
    # captcha_image.show()
    captcha_image = np.array(captcha_image)
#    print(captcha_image)
    return captcha_text, captcha_image
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
Beispiel #60
0
class OCRIter(mx.io.DataIter):
    def __init__(self, count, batch_size, num_label, init_states):
        super(OCRIter, self).__init__()
        global SEQ_LENGTH
        # you can get this font from http://font.ubuntu.com/
        self.captcha = ImageCaptcha(fonts=['./data/Xerox.ttf'])
        self.batch_size = batch_size
        self.count = count
        self.num_label = num_label
        self.init_states = init_states
        self.init_state_arrays = [mx.nd.zeros(x[1]) for x in init_states]
        self.provide_data = [('data', (batch_size, 80, 30))] + init_states
        self.provide_label = [('label', (self.batch_size, 4))]
        self.cache_data = []
        self.cache_label = []

    def __iter__(self):
        print('iter')
        init_state_names = [x[0] for x in self.init_states]
        for k in range(self.count):
            data = []
            label = []
            for i in range(self.batch_size):
                num = gen_rand()
                img = self.captcha.generate(num)
                img = np.fromstring(img.getvalue(), dtype='uint8')
                img = cv2.imdecode(img, cv2.IMREAD_GRAYSCALE)
                img = cv2.resize(img, (80, 30))
                img = img.transpose(1, 0)
                img = img.reshape((80, 30))
                img = np.multiply(img, 1 / 255.0)
                data.append(img)
                label.append(get_label(num))

            data_all = [mx.nd.array(data)] + self.init_state_arrays
            label_all = [mx.nd.array(label)]
            data_names = ['data'] + init_state_names
            label_names = ['label']

            data_batch = SimpleBatch(data_names, data_all, label_names, label_all)
            yield data_batch

    def reset(self):
        self.cache_data.clear()
        self.cache_label.clear()
        pass