当前位置:   article > 正文

tensorflow 实现端到端的OCR:二代身份证号识别_二代身份证数据集

二代身份证数据集

 

最近在研究OCR识别相关的东西,最终目标是能识别身份证上的所有中文汉字+数字,不过本文先设定一个小目标,先识别定长为18的身份证号,当然本文的思路也是可以复用来识别定长的验证码识别的。
本文实现思路主要来源于Xlvector的博客,采用基于CNN实现端到端的OCR,下面引用博文介绍目前基于深度学习的两种OCR识别方法:

  1. 把OCR的问题当做一个多标签学习的问题。4个数字组成的验证码就相当于有4个标签的图片识别问题(这里的标签还是有序的),用CNN来解决。
  1. 把OCR的问题当做一个语音识别的问题,语音识别是把连续的音频转化为文本,验证码识别就是把连续的图片转化为文本,用CNN+LSTM+CTC来解决。

这里方法1主要用来解决固定长度标签的图片识别问题,而方法2主要用来解决不定长度标签的图片识别问题,本文实现方法1识别固定18个数字字符的身份证号

环境依赖

  1. 本文基于tensorflow框架实现,依赖于tensorflow环境,建议使用anaconda进行python包管理及环境管理
  2. 本文使用freetype-py 进行训练集图片的实时生成,同时后续也可扩展为能生成中文字符图片的训练集,建议使用pip安装
  pip install freetype-py
  1. 同时本文还依赖于numpy和opencv等常用库
  pip install numpy cv2

知识准备

  1. 本文不具体介绍CNN (卷积神经网络)具体实现原理,不熟悉的建议参看集智博文卷积:如何成为一个很厉害的神经网络,这篇文章写得很?
  2. 本文实现思路很容易理解,就是把一个有序排列18个数字组成的图片当做一个多标签学习的问题,标签的长度可以任意改变,只要是固定长度的,这个训练方法都是适用的,当然现实中很多情况是需要识别不定长度的标签的,这部分就需要使用方法2(CNN+lSTM+CTC)来解决了。

正文

训练数据集生成

首先先完成训练数据集图片的生成,主要依赖于freetype-py库生成数字/中文的图片。其中要注意的一点是就是生成图片的大小,本文经过多次尝试后,生成的图片是32 x 256大小的,如果图片太大,则可能导致训练不收敛

生成出来的示例图片如下:

image.png

gen_image()方法返回
image_data:图片像素数据 (32,256)
label: 图片标签 18位数字字符 477081933151463759
vec : 图片标签转成向量表示 (180,) 代表每个数字所处的列,总长度 18 * 10

  1. #!/usr/bin/env python2
  2. # -*- coding: utf-8 -*-
  3. """
  4. 身份证文字+数字生成类
  5. @author: pengyuanjie
  6. """
  7. import numpy as np
  8. import freetype
  9. import copy
  10. import random
  11. import cv2
  12. class put_chinese_text(object):
  13. def __init__(self, ttf):
  14. self._face = freetype.Face(ttf)
  15. def draw_text(self, image, pos, text, text_size, text_color):
  16. '''
  17. draw chinese(or not) text with ttf
  18. :param image: image(numpy.ndarray) to draw text
  19. :param pos: where to draw text
  20. :param text: the context, for chinese should be unicode type
  21. :param text_size: text size
  22. :param text_color:text color
  23. :return: image
  24. '''
  25. self._face.set_char_size(text_size * 64)
  26. metrics = self._face.size
  27. ascender = metrics.ascender/64.0
  28. #descender = metrics.descender/64.0
  29. #height = metrics.height/64.0
  30. #linegap = height - ascender + descender
  31. ypos = int(ascender)
  32. if not isinstance(text, unicode):
  33. text = text.decode('utf-8')
  34. img = self.draw_string(image, pos[0], pos[1]+ypos, text, text_color)
  35. return img
  36. def draw_string(self, img, x_pos, y_pos, text, color):
  37. '''
  38. draw string
  39. :param x_pos: text x-postion on img
  40. :param y_pos: text y-postion on img
  41. :param text: text (unicode)
  42. :param color: text color
  43. :return: image
  44. '''
  45. prev_char = 0
  46. pen = freetype.Vector()
  47. pen.x = x_pos << 6 # div 64
  48. pen.y = y_pos << 6
  49. hscale = 1.0
  50. matrix = freetype.Matrix(int(hscale)*0x10000L, int(0.2*0x10000L),\
  51. int(0.0*0x10000L), int(1.1*0x10000L))
  52. cur_pen = freetype.Vector()
  53. pen_translate = freetype.Vector()
  54. image = copy.deepcopy(img)
  55. for cur_char in text:
  56. self._face.set_transform(matrix, pen_translate)
  57. self._face.load_char(cur_char)
  58. kerning = self._face.get_kerning(prev_char, cur_char)
  59. pen.x += kerning.x
  60. slot = self._face.glyph
  61. bitmap = slot.bitmap
  62. cur_pen.x = pen.x
  63. cur_pen.y = pen.y - slot.bitmap_top * 64
  64. self.draw_ft_bitmap(image, bitmap, cur_pen, color)
  65. pen.x += slot.advance.x
  66. prev_char = cur_char
  67. return image
  68. def draw_ft_bitmap(self, img, bitmap, pen, color):
  69. '''
  70. draw each char
  71. :param bitmap: bitmap
  72. :param pen: pen
  73. :param color: pen color e.g.(0,0,255) - red
  74. :return: image
  75. '''
  76. x_pos = pen.x >> 6
  77. y_pos = pen.y >> 6
  78. cols = bitmap.width
  79. rows = bitmap.rows
  80. glyph_pixels = bitmap.buffer
  81. for row in range(rows):
  82. for col in range(cols):
  83. if glyph_pixels[row*cols + col] != 0:
  84. img[y_pos + row][x_pos + col][0] = color[0]
  85. img[y_pos + row][x_pos + col][1] = color[1]
  86. img[y_pos + row][x_pos + col][2] = color[2]
  87. class gen_id_card(object):
  88. def __init__(self):
  89. #self.words = open('AllWords.txt', 'r').read().split(' ')
  90. self.number = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
  91. self.char_set = self.number
  92. #self.char_set = self.words + self.number
  93. self.len = len(self.char_set)
  94. self.max_size = 18
  95. self.ft = put_chinese_text('fonts/OCR-B.ttf')
  96. #随机生成字串,长度固定
  97. #返回text,及对应的向量
  98. def random_text(self):
  99. text = ''
  100. vecs = np.zeros((self.max_size * self.len))
  101. #size = random.randint(1, self.max_size)
  102. size = self.max_size
  103. for i in range(size):
  104. c = random.choice(self.char_set)
  105. vec = self.char2vec(c)
  106. text = text + c
  107. vecs[i*self.len:(i+1)*self.len] = np.copy(vec)
  108. return text,vecs
  109. #根据生成的text,生成image,返回标签和图片元素数据
  110. def gen_image(self):
  111. text,vec = self.random_text()
  112. img = np.zeros([32,256,3])
  113. color_ = (255,255,255) # Write
  114. pos = (0, 0)
  115. text_size = 21
  116. image = self.ft.draw_text(img, pos, text, text_size, color_)
  117. #仅返回单通道值,颜色对于汉字识别没有什么意义
  118. return image[:,:,2],text,vec
  119. #单字转向量
  120. def char2vec(self, c):
  121. vec = np.zeros((self.len))
  122. for j in range(self.len):
  123. if self.char_set[j] == c:
  124. vec[j] = 1
  125. return vec
  126. #向量转文本
  127. def vec2text(self, vecs):
  128. text = ''
  129. v_len = len(vecs)
  130. for i in range(v_len):
  131. if(vecs[i] == 1):
  132. text = text + self.char_set[i % self.len]
  133. return text
  134. if __name__ == '__main__':
  135. genObj = gen_id_card()
  136. image_data,label,vec = genObj.gen_image()
  137. cv2.imshow('image', image_data)
  138. cv2.waitKey(0)

构建网络,开始训练

首先定义生成一个batch的方法:

  1. # 生成一个训练batch
  2. def get_next_batch(batch_size=128):
  3. obj = gen_id_card()
  4. batch_x = np.zeros([batch_size, IMAGE_HEIGHT*IMAGE_WIDTH])
  5. batch_y = np.zeros([batch_size, MAX_CAPTCHA*CHAR_SET_LEN])
  6. for i in range(batch_size):
  7. image, text, vec = obj.gen_image()
  8. batch_x[i,:] = image.reshape((IMAGE_HEIGHT*IMAGE_WIDTH))
  9. batch_y[i,:] = vec
  10. return batch_x, batch_y

用了Batch Normalization,个人还不是很理解,读者可自行百度,代码来源于参考博文

  1. #Batch Normalization? 有空再理解,tflearn or slim都有封装
  2. ## http://stackoverflow.com/a/34634291/2267819
  3. def batch_norm(x, beta, gamma, phase_train, scope='bn', decay=0.9, eps=1e-5):
  4. with tf.variable_scope(scope):
  5. #beta = tf.get_variable(name='beta', shape=[n_out], initializer=tf.constant_initializer(0.0), trainable=True)
  6. #gamma = tf.get_variable(name='gamma', shape=[n_out], initializer=tf.random_normal_initializer(1.0, stddev), trainable=True)
  7. batch_mean, batch_var = tf.nn.moments(x, [0, 1, 2], name='moments')
  8. ema = tf.train.ExponentialMovingAverage(decay=decay)
  9. def mean_var_with_update():
  10. ema_apply_op = ema.apply([batch_mean, batch_var])
  11. with tf.control_dependencies([ema_apply_op]):
  12. return tf.identity(batch_mean), tf.identity(batch_var)
  13. mean, var = tf.cond(phase_train, mean_var_with_update, lambda: (ema.average(batch_mean), ema.average(batch_var)))
  14. normed = tf.nn.batch_normalization(x, mean, var, beta, gamma, eps)
  15. return normed

定义4层CNN和一层全连接层,卷积核分别是2层5x5、2层3x3,每层均使用tf.nn.relu非线性化,并使用max_pool,网络结构读者可自行调参优化

  1. # 定义CNN
  2. def crack_captcha_cnn(w_alpha=0.01, b_alpha=0.1):
  3. x = tf.reshape(X, shape=[-1, IMAGE_HEIGHT, IMAGE_WIDTH, 1])
  4. # 4 conv layer
  5. w_c1 = tf.Variable(w_alpha*tf.random_normal([5, 5, 1, 32]))
  6. b_c1 = tf.Variable(b_alpha*tf.random_normal([32]))
  7. conv1 = tf.nn.bias_add(tf.nn.conv2d(x, w_c1, strides=[1, 1, 1, 1], padding='SAME'), b_c1)
  8. conv1 = batch_norm(conv1, tf.constant(0.0, shape=[32]), tf.random_normal(shape=[32], mean=1.0, stddev=0.02), train_phase, scope='bn_1')
  9. conv1 = tf.nn.relu(conv1)
  10. conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
  11. conv1 = tf.nn.dropout(conv1, keep_prob)
  12. w_c2 = tf.Variable(w_alpha*tf.random_normal([5, 5, 32, 64]))
  13. b_c2 = tf.Variable(b_alpha*tf.random_normal([64]))
  14. conv2 = tf.nn.bias_add(tf.nn.conv2d(conv1, w_c2, strides=[1, 1, 1, 1], padding='SAME'), b_c2)
  15. conv2 = batch_norm(conv2, tf.constant(0.0, shape=[64]), tf.random_normal(shape=[64], mean=1.0, stddev=0.02), train_phase, scope='bn_2')
  16. conv2 = tf.nn.relu(conv2)
  17. conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
  18. conv2 = tf.nn.dropout(conv2, keep_prob)
  19. w_c3 = tf.Variable(w_alpha*tf.random_normal([3, 3, 64, 64]))
  20. b_c3 = tf.Variable(b_alpha*tf.random_normal([64]))
  21. conv3 = tf.nn.bias_add(tf.nn.conv2d(conv2, w_c3, strides=[1, 1, 1, 1], padding='SAME'), b_c3)
  22. conv3 = batch_norm(conv3, tf.constant(0.0, shape=[64]), tf.random_normal(shape=[64], mean=1.0, stddev=0.02), train_phase, scope='bn_3')
  23. conv3 = tf.nn.relu(conv3)
  24. conv3 = tf.nn.max_pool(conv3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
  25. conv3 = tf.nn.dropout(conv3, keep_prob)
  26. w_c4 = tf.Variable(w_alpha*tf.random_normal([3, 3, 64, 64]))
  27. b_c4 = tf.Variable(b_alpha*tf.random_normal([64]))
  28. conv4 = tf.nn.bias_add(tf.nn.conv2d(conv3, w_c4, strides=[1, 1, 1, 1], padding='SAME'), b_c4)
  29. conv4 = batch_norm(conv4, tf.constant(0.0, shape=[64]), tf.random_normal(shape=[64], mean=1.0, stddev=0.02), train_phase, scope='bn_4')
  30. conv4 = tf.nn.relu(conv4)
  31. conv4 = tf.nn.max_pool(conv4, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
  32. conv4 = tf.nn.dropout(conv4, keep_prob)
  33. # Fully connected layer
  34. w_d = tf.Variable(w_alpha*tf.random_normal([2*16*64, 1024]))
  35. b_d = tf.Variable(b_alpha*tf.random_normal([1024]))
  36. dense = tf.reshape(conv4, [-1, w_d.get_shape().as_list()[0]])
  37. dense = tf.nn.relu(tf.add(tf.matmul(dense, w_d), b_d))
  38. dense = tf.nn.dropout(dense, keep_prob)
  39. w_out = tf.Variable(w_alpha*tf.random_normal([1024, MAX_CAPTCHA*CHAR_SET_LEN]))
  40. b_out = tf.Variable(b_alpha*tf.random_normal([MAX_CAPTCHA*CHAR_SET_LEN]))
  41. out = tf.add(tf.matmul(dense, w_out), b_out)
  42. return out

最后执行训练,使用sigmoid分类,每100次计算一次准确率,如果准确率超过80%,则保存模型并结束训练

  1. # 训练
  2. def train_crack_captcha_cnn():
  3. output = crack_captcha_cnn()
  4. # loss
  5. #loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=output, labels=Y))
  6. loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=output, labels=Y))
  7. # 最后一层用来分类的softmax和sigmoid有什么不同?
  8. # optimizer 为了加快训练 learning_rate应该开始大,然后慢慢衰
  9. optimizer = tf.train.AdamOptimizer(learning_rate=0.002).minimize(loss)
  10. predict = tf.reshape(output, [-1, MAX_CAPTCHA, CHAR_SET_LEN])
  11. max_idx_p = tf.argmax(predict, 2)
  12. max_idx_l = tf.argmax(tf.reshape(Y, [-1, MAX_CAPTCHA, CHAR_SET_LEN]), 2)
  13. correct_pred = tf.equal(max_idx_p, max_idx_l)
  14. accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
  15. saver = tf.train.Saver()
  16. with tf.Session() as sess:
  17. sess.run(tf.global_variables_initializer())
  18. step = 0
  19. while True:
  20. batch_x, batch_y = get_next_batch(64)
  21. _, loss_ = sess.run([optimizer, loss], feed_dict={X: batch_x, Y: batch_y, keep_prob: 0.75, train_phase:True})
  22. print(step, loss_)
  23. # 每100 step计算一次准确率
  24. if step % 100 == 0 and step != 0:
  25. batch_x_test, batch_y_test = get_next_batch(100)
  26. acc = sess.run(accuracy, feed_dict={X: batch_x_test, Y: batch_y_test, keep_prob: 1., train_phase:False})
  27. print "第%s步,训练准确率为:%s" % (step, acc)
  28. # 如果准确率大80%,保存模型,完成训练
  29. if acc > 0.8:
  30. saver.save(sess, "crack_capcha.model", global_step=step)
  31. break
  32. step += 1

执行结果,笔者在大概500次训练后,得到准确率84.3%的结果

image.png

大概训练1500~2200次左右,准确率就能达到98%,打印前5条测试样本可以看出,输出结果基本与label一致了

image.png

后记

最后所有代码和字体资源文件托管在我的Github

笔者在一开始训练的时候图片大小是64 x 512的,训练的时候发现训练速度很慢,而且训练的loss不收敛一直保持在0.33左右,缩小图片为32 x 256后解决,不知道为啥,猜测要么是网络层级不够,或者特征层数不够吧。

小目标完成后,为了最终目标的完成,后续可能尝试方法2,去识别不定长的中文字符图片,不过要先去理解LSTM网络和 CTC模型了。

参考链接

TensorFlow练习20: 使用深度学习破解字符验证码
Python2.x上使用freetype实现OpenCV2.x的中文输出
端到端的OCR:基于CNN的实现

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号