This time to bring you the Python identification verification code, Python identification Verification Code of note what, the following is the actual case, together to see.
In addition to the traditional PIL package processing pictures, and then using PYTESSERT+OCR to identify the accident, you can also use Tessorflow training to identify the verification code.
Most of this code is reproduced, only a few places changed.
The code is running in a Linux environment, Tessorflow does not support Windows Python 2.7.
gen_captcha.py code.
#coding =utf-8from captcha.image Import Imagecaptcha # pip install captchaimport numpy as Npimport Matplotlib.pyplot as Plt From PIL import Imageimport random# The characters in the verification code, you do not have the kanji number = [' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ']alphabet = [ ' 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 ']alphabet = [' 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 ', ' ' number=[' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ']alphabet =[]alphabet =[] ' # CAPTCHA is generally case-insensitive; Captcha length 4 characters def random_captcha_text (char_set=number + alphabet + alphabet, captcha_size=4): Captcha_text = [] for I I N Range (captcha_size): c = Random.choice (Char_set) captcha_text.append (c) return captcha_text# generate a character corresponding to the verification code def GEN_CA Ptcha_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 ') # write to file 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_imageif name = = ' main ': # Test text, image = Gen_captcha_text_and_image () print I Mage Gray = Np.mean (image,-1) Print gray print image.shape print gray.shape f = plt.figure () ax = F.add_subplot (111 ) Ax.text (0.1, 0.9, text, ha= ' center ', va= ' center ', transform=ax.transaxes) plt.imshow (image) Plt.show ()
train.py code.
#coding =utf-8from gen_captcha Import gen_captcha_text_and_imagefrom gen_captcha import numberfrom gen_captcha Import Alphabetfrom Gen_captcha import alphabetimport numpy as Npimport TensorFlow as TF "" "text, image = Gen_captcha_text_and_ima GE () print "CAPTCHA image channel:", Image.shape # (60, 160, 3) # image size Image_height = 60image_width = 160max_captcha = Len (text) print "Maximum number of characters in captcha text", Max_captcha # Verification code up to 4 characters; I am all fixed to 4, can not be fixed. If the code length is less than 4, use ' _ ' to Complement "" "image_height = 60image_width = 160max_captcha = 4# color image to grayscale image (color is not used for identification verification code) def convert2gray (IMG) : If Len (img.shape) > 2:gray = Np.mean (img,-1) # The above method is faster, the normal transfer method is as follows # R, G, B = img[:,:,0], img[:,:,1], img[:,: , 2] # Gray = 0.2989 * r + 0.5870 * g + 0.1140 * b return Gray else:return img "" "CNN has the highest performance when the image size is a multiple of 2, if you are using an image size that is not Multiples of 2, which can complement useless pixels at the edge of the image. Np.pad (Image, ((2,3), (2,2)), ' Constant ', constant_values= (255,)) # Fill 2 lines on the image, fill 3 lines, left to fill 2 lines, right to fill 2 lines "" "" # text Steering Char_set = number + Alphabet + Alphabet + [' _ '] # If the captcha length is less than 4, ' _ ' is used to complement Char_set_len = LEN (char_set) def text2vEC (Text): Text_len = len (text) if Text_len > Max_captcha:raise valueerror (' captcha maximum 4 characters ') vector = Np.zeros (max_cap Tcha * Char_set_len) def char2pos (c): if c = = ' _ ': K = return k K = Ord (c)-If k > 9:k = Ord (c)-if k > 35:k = Ord (c)-if k > 61:raise valueerror (' No Map ') retur n k for I, C in enumerate (text): #print text idx = i * Char_set_len + char2pos (c) #print I,char_set_len,char2pos (c), idx vector[idx] = 1 return vector#print text2vec (' 1az_ ') # vector reversal text def vec2text (VEC): Char_pos = Vec.nonzero () [0] t ext = [] for I, C in enumerate (char_pos): Char_at_pos = i # c/63 char_idx = c% Char_set_len if Char_idx < 10 : Char_code = char_idx + ord (' 0 ') elif char_idx < 36:char_code = char_idx-10 + ord (' A ') elif char_id x < 62:char_code = char_idx-36 + ord (' a ') elif Char_idx = = 62:char_code = Ord ('_') else:raise ValueError (' ERROR ')Text.append (Char_code) return "". Join (text) "" "#向量 (size Max_captcha*char_set_len) encode one character per 63 encoded with 0,1, so smooth as to have, characters also have VEC = Text2vec ("f5sd") Text = Vec2text (VEC) print (text) # F5sdvec = Text2vec ("SFd5") Text = Vec2text (VEC) print (text) # SFd5 "" "# Raw into a training batchdef Get_next_batch (batch_size=128): batch_x = Np.zeros ([Batch_size, Image_height * image_width]) batch_y = NP. Zeros ([Batch_size, Max_captcha * Char_set_len]) # Sometimes generate image size is not (3) def wrap_gen_captcha_text_and_image (): While True:text, image = Gen_captcha_text_and_image () if Image.shape = = (3): Return text, image for I in range (batch_size): text, image = Wrap_gen_captcha_text_and_image () image = Convert2gray (image) Batch_x[i,: ] = Image.flatten ()/255 # (Image.flatten () -128)/128 mean is 0 batch_y[i,:] = Text2vec (text) return batch_x, batch_y### ################################################################ #X = Tf.placeholder (Tf.float32, [None, IMAGE_ HEIGHT * Image_width]) Y = Tf.placeholder (TF.Float32, [None, Max_captcha * Char_set_len]) Keep_prob = Tf.placeholder (tf.float32) # dropout# definition cnndef crack_captcha_cnn (w_alpha=0.01, b_alpha=0.1): x = Tf.reshape (x, Shape=[-1, Image_height, Image_width, 1]) # W_c1_alpha = Np.sqrt (2.0/(IMA Ge_height*image_width)) # # W_c2_alpha = np.sqrt (2.0/(3*3*32)) # W_c3_alpha = Np.sqrt (2.0/(3*3*64)) # W_d1_alpha = Np.s qRT (2.0/(8*32*64)) # Out_alpha = Np.sqrt (2.0/1024) # 3 conv Layer w_c1 = tf. Variable (W_alpha * Tf.random_normal ([3, 3, 1, +])) B_C1 = tf. Variable (B_alpha * Tf.random_normal ([+]) Conv1 = Tf.nn.relu (Tf.nn.bias_add (tf.nn.conv2d (x, W_c1, strides=[1, 1, 1, 1), Padding= ' same '), b_c1)) Conv1 = Tf.nn.max_pool (Conv1, Ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding= ' same ') Conv1 = Tf.nn.dropout (CONV1, keep_prob) w_c2 = tf. Variable (W_alpha * Tf.random_normal ([3, 3, +])) B_C2 = tf. Variable (B_alpha * Tf.random_normal ([+])) Conv2 = Tf.nn.relu (Tf.nn.bias_add (tf.nn.conv2d, Conv1, W_C2, 1, 1 , 1], padding= ' same '),B_C2)) Conv2 = Tf.nn.max_pool (Conv2, Ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding= ' same ') Conv2 = Tf.nn.dropout (con V2, keep_prob) w_c3 = tf. Variable (W_alpha * Tf.random_normal ([3, 3, +])) B_C3 = tf. Variable (B_alpha * Tf.random_normal ([+])) Conv3 = Tf.nn.relu (Tf.nn.bias_add (tf.nn.conv2d, Conv2, W_C3, 1, 1 , 1], padding= ' same '), b_c3)) Conv3 = Tf.nn.max_pool (Conv3, Ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding= ' same ') CO Nv3 = Tf.nn.dropout (Conv3, Keep_prob) # Fully connected layer w_d = tf. Variable (W_alpha * TF.RANDOM_NORMAL ([8 * + * +, 1024x768])) B_d = tf. Variable (B_alpha * Tf.random_normal ([1024x768])) dense = Tf.reshape (Conv3, [-1, W_d.get_shape (). As_list () [0]]) dense = Tf.nn . Relu (Tf.add (Tf.matmul (dense, w_d), b_d)) dense = tf.nn.dropout (dense, keep_prob) w_out = tf. Variable (W_alpha * Tf.random_normal ([1024x768, Max_captcha * Char_set_len]) B_out = tf. Variable (B_alpha * TF.RANDOM_NORMAL ([Max_captcha * Char_set_len])) out = Tf.add (Tf.matmul (Dense, w_out), b_out) # out = Tf.nn.softmax (out) return out# training def TRAIN_CRACK_CAPTCHA_CNN (): Import Time Start_time=time.time () Output = CRACK_CAPTCHA_CNN () # Loss #loss = Tf.reduce_mean (tf.nn.softmax_cross_entropy_with_logits (output, Y)) loss = T F.reduce_mean (Tf.nn.sigmoid_cross_entropy_with_logits (Logits=output, labels=y)) # What is the difference between the last layer of Softmax and sigmoid used for classification? # Optimizer in order to speed up the training learning_rate should start big, then slowly decay optimizer = Tf.train.AdamOptimizer (learning_rate=0.001). Minimize (loss) predict = Tf.reshape (output, [-1, Max_captcha, Char_set_len]) max_idx_p = Tf.argmax (predict, 2) max_idx_l = Tf.argmax (tf . Reshape (Y, [-1, Max_captcha, Char_set_len]), 2) correct_pred = Tf.equal (max_idx_p, max_idx_l) accuracy = Tf.reduce_mean (Tf.cast (correct_pred, tf.float32)) saver = Tf.train.Saver () with TF. Session () as Sess:sess.run (Tf.global_variables_initializer ()) step = 0 while true:batch_x, batch_y = Get_n Ext_batch _, Loss_ = Sess.run ([Optimizer, loss], feed_dict={x:batch_x, Y:batCh_y, keep_prob:0.75}) Print Time.strftime ('%y-%m-%d%h:%m:%s ', Time.localtime (Time.time ())), step, Loss_ # per 100 Step calculates the exact rate if step% = = 0:batch_x_test, Batch_y_test = Get_next_batch (+) acc = Sess.run (Accurac Y, Feed_dict={x:batch_x_test, Y:batch_y_test, Keep_prob:1.}) Print U ' ******************************************* The accuracy rate for%s times is%s '% (step, ACC) # If the accuracy is greater than 50%, save the model, complete the training if ACC > 0.9: # #我这里设了0.9, set the larger The longer the training takes, the more difficult it is to achieve it if it is set too close to 1. If you use the CPU, it takes a long time and the CPU is very high and the computer is hot. Saver.save (Sess, "Crack_capcha.model", Global_step=step) print time.time ()-start_time break Step + = 1TRAIN_CRACK_CAPTCHA_CNN ()
Test code:
Output = CRACK_CAPTCHA_CNN () saver = Tf.train.Saver () Sess = tf. Session () Saver.restore (Sess, Tf.train.latest_checkpoint ('. ')) while (1): text, image = Gen_captcha_text_and_image () image = Convert2gray (image) image = Image.flatten ()/ 255 predict = Tf.argmax (tf.reshape (output, [-1, Max_captcha, Char_set_len]), 2) text_list = Sess.run (predict, FEED_DICT={X: [Image], keep_prob:1}) Predict_text = text_list[0].tolist () vector = Np.zeros (Max_captcha * CHAR _set_len) i = 0 for t in Predict_text: vector[i * + t] = 1 i + = 1 # break print ("Correct: {} forecast: {} ". Format (text, vec2text (vector)))
If you want to quickly test the code effect, verify that the character of the code is not set too much, such as 0123 of these numbers can be.
Believe that you have read the case of this article you have mastered the method, more exciting please pay attention to the PHP Chinese network other related articles!
Recommended reading:
How does python achieve the Markov distance
Python how to bulk read TXT file to dataframe format