引言:

过去几周我一直在涉足深度学习领域,尤其是卷积神经网络模型。最近,谷歌围绕街景多位数字识别技术发布了一篇不错的paper。该文章描述了一个用于提取街景门牌号的单个端到端神经网络系统。然后,作者阐述了基于同样的网络结构如何来突破谷歌验证码识别系统的准确率。
为了亲身体验神经网络的实现,我决定尝试设计一个可以解决类似问题的系统:国内车牌号自动识别系统。设计这样一个系统的原因有3点:

  • 我应该能够参照谷歌那篇paper搭建一个同样的或者类似的网络架构:谷歌提供的那个网络架构在验证码识别上相当不错,那么讲道理的话,用它来识别车牌号应该也会很给力。拥有一个知名的网络架构将会大大地简化我学习CNN的步骤。
  • 我可以很容易地生成训练数据(车牌数)。训练神经网络存在一个很大的问题就是需要大量的标签样本。通常要训练好一个网络就需要几十万张标记过的图片。 
  • 好奇心。传统的车牌号自动识别系统依赖于自己编写算法来实现车牌定位,标准化,分割和字符识别等功能。照这样的话,实现这些系统的代码可能达到上千行。然而,我比较感兴趣的是,如何使用相对较少的代码和最少的专业领域知识来开发一个不错的系统。

开发该项目的环境要求有Python,Tensorflow,OpenCV和NumPy等软件。源代码在这里

首先项目结构及成果图:

合成图片

genplate.py

为了训练任何一个神经网络,必须提供一套拥有正确输出的训练数据。 

 

文本和车牌背景国内正常的车牌格式,但是文本颜色必须比车牌颜色更深一些。这是为了模拟真实场景的光线变化。最后再加入一些噪音,这样不仅能够解释真实传感器的噪音,而且能够避免过多依赖于锐化的轮廓边界而看到的将会是离焦的输入图片。font目录导入了字体包、image导入了车牌背景及噪声图片。

 

车牌变换采用了一种基于随机滚转、倾斜、偏转、平移以及缩放的仿射变换。每个参数允许的范围是车牌号可能被看到的所有情况的集合。比如,偏转比滚转允许变化更多(你更可能看到一辆汽车在拐弯而不是翻转到一边)。

  1. import PIL
  2. from PIL import ImageFont
  3. from PIL import Image
  4. from PIL import ImageDraw
  5. import cv2;
  6. import numpy as np;
  7. import os;
  8. from math import *
  9. # 生成车牌
  10. # font = ImageFont.truetype("Arial-Bold.ttf",14)
  11. index = {"京": 0, "沪": 1, "津": 2, "渝": 3, "冀": 4, "晋": 5, "蒙": 6, "辽": 7, "吉": 8, "黑": 9, "苏": 10, "浙": 11, "皖": 12,
  12. "闽": 13, "赣": 14, "鲁": 15, "豫": 16, "鄂": 17, "湘": 18, "粤": 19, "桂": 20, "琼": 21, "川": 22, "贵": 23, "云": 24,
  13. "藏": 25, "陕": 26, "甘": 27, "青": 28, "宁": 29, "新": 30, "0": 31, "1": 32, "2": 33, "3": 34, "4": 35, "5": 36,
  14. "6": 37, "7": 38, "8": 39, "9": 40, "A": 41, "B": 42, "C": 43, "D": 44, "E": 45, "F": 46, "G": 47, "H": 48,
  15. "J": 49, "K": 50, "L": 51, "M": 52, "N": 53, "P": 54, "Q": 55, "R": 56, "S": 57, "T": 58, "U": 59, "V": 60,
  16. "W": 61, "X": 62, "Y": 63, "Z": 64};
  17. chars = ["京", "沪", "津", "渝", "冀", "晋", "蒙", "辽", "吉", "黑", "苏", "浙", "皖", "闽", "赣", "鲁", "豫", "鄂", "湘", "粤", "桂",
  18. "琼", "川", "贵", "云", "藏", "陕", "甘", "青", "宁", "新", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A",
  19. "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X",
  20. "Y", "Z"
  21. ];
  22. def AddSmudginess(img, Smu):
  23. rows = r(Smu.shape[0] - 50)
  24. cols = r(Smu.shape[1] - 50)
  25. adder = Smu[rows:rows + 50, cols:cols + 50];
  26. adder = cv2.resize(adder, (50, 50));
  27. # adder = cv2.bitwise_not(adder)
  28. img = cv2.resize(img,(50,50))
  29. img = cv2.bitwise_not(img)
  30. img = cv2.bitwise_and(adder, img)
  31. img = cv2.bitwise_not(img)
  32. return img
  33. def rot(img,angel,shape,max_angel):
  34. """ 使图像轻微的畸变
  35. img 输入图像
  36. factor 畸变的参数
  37. size 为图片的目标尺寸
  38. """
  39. size_o = [shape[1],shape[0]]
  40. size = (shape[1]+ int(shape[0]*cos((float(max_angel )/180) * 3.14)),shape[0])
  41. interval = abs( int( sin((float(angel) /180) * 3.14)* shape[0]));
  42. pts1 = np.float32([[0,0],[0,size_o[1]],[size_o[0],0],[size_o[0],size_o[1]]])
  43. if(angel>0):
  44. pts2 = np.float32([[interval,0],[0,size[1] ],[size[0],0 ],[size[0]-interval,size_o[1]]])
  45. else:
  46. pts2 = np.float32([[0,0],[interval,size[1] ],[size[0]-interval,0 ],[size[0],size_o[1]]])
  47. M = cv2.getPerspectiveTransform(pts1,pts2);
  48. dst = cv2.warpPerspective(img,M,size);
  49. return dst;
  50. def rotRandrom(img, factor, size):
  51. shape = size;
  52. pts1 = np.float32([[0, 0], [0, shape[0]], [shape[1], 0], [shape[1], shape[0]]])
  53. pts2 = np.float32([[r(factor), r(factor)], [ r(factor), shape[0] - r(factor)], [shape[1] - r(factor), r(factor)],
  54. [shape[1] - r(factor), shape[0] - r(factor)]])
  55. M = cv2.getPerspectiveTransform(pts1, pts2);
  56. dst = cv2.warpPerspective(img, M, size);
  57. return dst;
  58. def tfactor(img):
  59. hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV);
  60. hsv[:,:,0] = hsv[:,:,0]*(0.8+ np.random.random()*0.2);
  61. hsv[:,:,1] = hsv[:,:,1]*(0.3+ np.random.random()*0.7);
  62. hsv[:,:,2] = hsv[:,:,2]*(0.2+ np.random.random()*0.8);
  63. img = cv2.cvtColor(hsv,cv2.COLOR_HSV2BGR);
  64. return img
  65. def random_envirment(img,data_set):
  66. index=r(len(data_set))
  67. env = cv2.imread(data_set[index])
  68. env = cv2.resize(env,(img.shape[1],img.shape[0]))
  69. bak = (img==0);
  70. bak = bak.astype(np.uint8)*255;
  71. inv = cv2.bitwise_and(bak,env)
  72. img = cv2.bitwise_or(inv,img)
  73. return img
  74. def GenCh(f,val):
  75. img=Image.new("RGB", (45,70),(255,255,255))
  76. draw = ImageDraw.Draw(img)
  77. draw.text((0, 3),val,(0,0,0),font=f)
  78. img = img.resize((23,70))
  79. A = np.array(img)
  80. return A
  81. def GenCh1(f,val):
  82. img=Image.new("RGB", (23,70),(255,255,255))
  83. draw = ImageDraw.Draw(img)
  84. #draw.text((0, 2),val.decode('utf-8'),(0,0,0),font=f)
  85. draw.text((0, 2),val,(0,0,0),font=f)
  86. A = np.array(img)
  87. return A
  88. def AddGauss(img, level):
  89. return cv2.blur(img, (level * 2 + 1, level * 2 + 1));
  90. def r(val):
  91. return int(np.random.random() * val)
  92. def AddNoiseSingleChannel(single):
  93. diff = 255-single.max();
  94. noise = np.random.normal(0,1+r(6),single.shape);
  95. noise = (noise - noise.min())/(noise.max()-noise.min())
  96. noise= diff*noise;
  97. noise= noise.astype(np.uint8)
  98. dst = single + noise
  99. return dst
  100. def addNoise(img,sdev = 0.5,avg=10):
  101. img[:,:,0] = AddNoiseSingleChannel(img[:,:,0]);
  102. img[:,:,1] = AddNoiseSingleChannel(img[:,:,1]);
  103. img[:,:,2] = AddNoiseSingleChannel(img[:,:,2]);
  104. return img;
  105. class GenPlate:
  106. def __init__(self,fontCh,fontEng,NoPlates):
  107. self.fontC = ImageFont.truetype(fontCh,43,0);
  108. self.fontE = ImageFont.truetype(fontEng,60,0);
  109. self.img=np.array(Image.new("RGB", (226,70),(255,255,255)))
  110. self.bg = cv2.resize(cv2.imread("./images/template.bmp"),(226,70));
  111. self.smu = cv2.imread("./images/smu2.jpg");
  112. self.noplates_path = [];
  113. for parent,parent_folder,filenames in os.walk(NoPlates):
  114. for filename in filenames:
  115. path = parent+"/"+filename;
  116. self.noplates_path.append(path);
  117. def draw(self,val):
  118. offset= 2 ;
  119. self.img[0:70,offset+8:offset+8+23]= GenCh(self.fontC,val[0]);
  120. self.img[0:70,offset+8+23+6:offset+8+23+6+23]= GenCh1(self.fontE,val[1]);
  121. for i in range(5):
  122. base = offset+8+23+6+23+17 +i*23 + i*6 ;
  123. self.img[0:70, base : base+23]= GenCh1(self.fontE,val[i+2]);
  124. return self.img
  125. def generate(self,text):
  126. if len(text) == 7:
  127. fg = self.draw(text.encode('utf-8').decode(encoding="utf-8"));
  128. fg = cv2.bitwise_not(fg);
  129. com = cv2.bitwise_or(fg,self.bg);
  130. com = rot(com,r(60)-30,com.shape,30);
  131. com = rotRandrom(com,10,(com.shape[1],com.shape[0]));
  132. #com = AddSmudginess(com,self.smu)
  133. com = tfactor(com)
  134. com = random_envirment(com,self.noplates_path);
  135. com = AddGauss(com, 1+r(4));
  136. com = addNoise(com);
  137. return com
  138. def genPlateString(self,pos,val):
  139. plateStr = "";
  140. box = [0,0,0,0,0,0,0];
  141. if(pos!=-1):
  142. box[pos]=1;
  143. for unit,cpos in zip(box,range(len(box))):
  144. if unit == 1:
  145. plateStr += val
  146. else:
  147. if cpos == 0:
  148. plateStr += chars[r(31)]
  149. elif cpos == 1:
  150. plateStr += chars[41+r(24)]
  151. else:
  152. plateStr += chars[31 + r(34)]
  153. return plateStr;
  154. def genBatch(self, batchSize,pos,charRange, outputPath,size):
  155. if (not os.path.exists(outputPath)):
  156. os.mkdir(outputPath)
  157. for i in range(batchSize):
  158. plateStr = G.genPlateString(-1,-1)
  159. img = G.generate(plateStr);
  160. img = cv2.resize(img,size);
  161. cv2.imwrite(outputPath + "/" + str(i).zfill(2) + ".jpg", img);
  162. # return img
  163. G = GenPlate("./font/platech.ttf",'./font/platechar.ttf',"./NoPlates")
  164. G.genBatch(15,2,range(31,65),"./plate",(272,72)) #注释原因为每次其他模块运行,若导入该库,都会刷性该函数

inputdata.py 省略....

产生用于训练的数据
# 批量生成车牌,供算法调用

 

 

网络结构  # 算法的核心,卷积神经网络

使用的卷积神经网络结构如model.py所示:

  1. import tensorflow as tf
  2. import numpy as np
  3. # 算法的核心,卷积神经网络
  4. def inference (images,keep_prob):
  5. '''
  6. Build the model
  7. Args:
  8. image: image batch,4D tensor,tf.float32,[batch_size,height,width,channels]
  9. Returns:
  10. output tensor with the computed logits,float,[batch_size,65]
  11. '''
  12. # conv1
  13. with tf.variable_scope('conv1') as scope:
  14. weights = tf.get_variable('weights',
  15. shape = [3,3,3,32],
  16. dtype = tf.float32,
  17. initializer=tf.truncated_normal_initializer(stddev=0.1,dtype=tf.float32))
  18. conv = tf.nn.conv2d(images,weights,strides=[1,1,1,1],padding='VALID')
  19. biases = tf.get_variable('biases',
  20. shape=[32],
  21. dtype=tf.float32,
  22. initializer=tf.constant_initializer(0.1))
  23. pre_activation = tf.nn.bias_add(conv,biases)
  24. conv1 = tf.nn.relu(pre_activation,name= scope.name)
  25. # conv2
  26. with tf.variable_scope('conv2') as scope:
  27. weights = tf.get_variable('weights',shape=[3,3,32,32],dtype=tf.float32,initializer=tf.truncated_normal_initializer(stddev=0.1,dtype=tf.float32))
  28. conv = tf.nn.conv2d(conv1,weights,strides=[1,1,1,1],padding='VALID')
  29. biases = tf.get_variable('biases',
  30. shape=[32],
  31. dtype=tf.float32,
  32. initializer=tf.constant_initializer(0.1))
  33. pre_activation = tf.nn.bias_add(conv,biases)
  34. conv2 = tf.nn.relu(pre_activation,name= scope.name)
  35. with tf.variable_scope('max_pooling1') as scope:
  36. pool1 = tf.nn.max_pool(conv2,ksize = [1,2,2,1],strides= [1,2,2,1],padding='VALID',name='pooling1')
  37. #conv3
  38. with tf.variable_scope('conv3') as scope:
  39. weights = tf.get_variable('weights',shape=[3,3,32,64],dtype=tf.float32,initializer=tf.truncated_normal_initializer(stddev=0.1,dtype=tf.float32))
  40. conv = tf.nn.conv2d(pool1,weights,strides=[1,1,1,1],padding='VALID')
  41. biases = tf.get_variable('biases',shape=[64],dtype = tf.float32,initializer= tf.constant_initializer(0.1))
  42. pre_activation = tf.nn.bias_add(conv,biases)
  43. conv3 = tf.nn.relu(pre_activation,name=scope.name)
  44. #conv4
  45. with tf.variable_scope('conv4') as scope:
  46. weights = tf.get_variable('weights',shape=[3,3,64,64],dtype=tf.float32,initializer=tf.truncated_normal_initializer(stddev=0.1,dtype=tf.float32))
  47. conv =tf.nn.conv2d(conv3,weights,strides=[1,1,1,1],padding='VALID')
  48. biases = tf.get_variable('biases',shape=[64],dtype=tf.float32,initializer=tf.constant_initializer(0.1))
  49. pre_activation = tf.nn.bias_add(conv,biases)
  50. conv4 = tf.nn.relu(pre_activation,name=scope.name)
  51. with tf.variable_scope('max_pooling2') as scope:
  52. pool2 = tf.nn.max_pool(conv4,ksize=[1,2,2,1],strides=[1,2,2,1],padding='VALID',name='pooling2')
  53. #conv5
  54. with tf.variable_scope('conv5') as scope:
  55. weights = tf.get_variable('weights',shape=[3,3,64,128],dtype=tf.float32,initializer=tf.truncated_normal_initializer(stddev=0.1,dtype=tf.float32))
  56. conv =tf.nn.conv2d(pool2,weights,strides=[1,1,1,1],padding='VALID')
  57. biases = tf.get_variable('biases',shape=[128],dtype=tf.float32,initializer=tf.constant_initializer(0.1))
  58. pre_activation = tf.nn.bias_add(conv,biases)
  59. conv5 = tf.nn.relu(pre_activation,name=scope.name)
  60. #conv6
  61. with tf.variable_scope('conv6') as scope:
  62. weights = tf.get_variable('weights',shape=[3,3,128,128],dtype=tf.float32,initializer=tf.truncated_normal_initializer(stddev=0.1,dtype=tf.float32))
  63. conv =tf.nn.conv2d(conv5,weights,strides=[1,1,1,1],padding='VALID')
  64. biases = tf.get_variable('biases',shape=[128],dtype=tf.float32,initializer=tf.constant_initializer(0.1))
  65. pre_activation = tf.nn.bias_add(conv,biases)
  66. conv6 = tf.nn.relu(pre_activation,name=scope.name)
  67. #pool3
  68. with tf.variable_scope('max_pool3') as scope:
  69. pool3 = tf.nn.max_pool(conv6,ksize=[1,2,2,1],strides=[1,2,2,1],padding='VALID',name='pool3')
  70. #%%
  71. #fc1_flatten
  72. with tf.variable_scope('fc1') as scope:
  73. shp = pool3.get_shape()
  74. flattened_shape =shp[1].value*shp[2].value*shp[3].value
  75. reshape = tf.reshape(pool3,[-1,flattened_shape])
  76. fc1 = tf.nn.dropout(reshape,keep_prob,name='fc1_dropdot')
  77. # 全连接层
  78. # 第一个全连接层,识别车牌上的省
  79. with tf.variable_scope('fc21') as scope:
  80. weights = tf.get_variable('weights',
  81. shape=[flattened_shape,65],
  82. dtype=tf.float32,
  83. initializer=tf.truncated_normal_initializer(stddev=0.005,dtype=tf.float32))
  84. biases = tf.get_variable('biases',
  85. shape=[65],
  86. dtype=tf.float32,
  87. initializer = tf.truncated_normal_initializer(0.1)
  88. )
  89. fc21 = tf.matmul(fc1,weights)+biases
  90. # 第二个全连接层,识别车牌上的市
  91. with tf.variable_scope('fc22') as scope:
  92. weights = tf.get_variable('weights',
  93. shape=[flattened_shape,65],
  94. dtype=tf.float32,
  95. initializer=tf.truncated_normal_initializer(stddev=0.005,dtype=tf.float32))
  96. biases = tf.get_variable('biases',
  97. shape=[65],
  98. dtype=tf.float32,
  99. initializer = tf.truncated_normal_initializer(0.1)
  100. )
  101. fc22 = tf.matmul(fc1,weights)+biases
  102. # 第三个全连接层,识别车牌第三位的字母或者数字
  103. with tf.variable_scope('fc23') as scope:
  104. weights = tf.get_variable('weights',
  105. shape=[flattened_shape,65],
  106. dtype=tf.float32,
  107. initializer=tf.truncated_normal_initializer(stddev=0.005,dtype=tf.float32))
  108. biases = tf.get_variable('biases',
  109. shape=[65],
  110. dtype=tf.float32,
  111. initializer = tf.truncated_normal_initializer(0.1)
  112. )
  113. fc23= tf.matmul(fc1,weights)+biases
  114. with tf.variable_scope('fc24') as scope:
  115. weights = tf.get_variable('weights',
  116. shape=[flattened_shape,65],
  117. dtype=tf.float32,
  118. initializer=tf.truncated_normal_initializer(stddev=0.005,dtype=tf.float32))
  119. biases = tf.get_variable('biases',
  120. shape=[65],
  121. dtype=tf.float32,
  122. initializer = tf.truncated_normal_initializer(0.1)
  123. )
  124. fc24 = tf.matmul(fc1,weights)+biases
  125. with tf.variable_scope('fc25') as scope:
  126. weights = tf.get_variable('weights',
  127. shape=[flattened_shape,65],
  128. dtype=tf.float32,
  129. initializer=tf.truncated_normal_initializer(stddev=0.005,dtype=tf.float32))
  130. biases = tf.get_variable('biases',
  131. shape=[65],
  132. dtype=tf.float32,
  133. initializer = tf.truncated_normal_initializer(0.1)
  134. )
  135. fc25 = tf.matmul(fc1,weights)+biases
  136. with tf.variable_scope('fc26') as scope:
  137. weights = tf.get_variable('weights',
  138. shape=[flattened_shape,65],
  139. dtype=tf.float32,
  140. initializer=tf.truncated_normal_initializer(stddev=0.005,dtype=tf.float32))
  141. biases = tf.get_variable('biases',
  142. shape=[65],
  143. dtype=tf.float32,
  144. initializer = tf.truncated_normal_initializer(0.1)
  145. )
  146. fc26 = tf.matmul(fc1,weights)+biases
  147. with tf.variable_scope('fc27') as scope:
  148. weights = tf.get_variable('weights',
  149. shape=[flattened_shape,65],
  150. dtype=tf.float32,
  151. initializer=tf.truncated_normal_initializer(stddev=0.005,dtype=tf.float32))
  152. biases = tf.get_variable('biases',
  153. shape=[65],
  154. dtype=tf.float32,
  155. initializer = tf.truncated_normal_initializer(0.1)
  156. )
  157. fc27 = tf.matmul(fc1,weights)+biases
  158. return fc21,fc22,fc23,fc24,fc25,fc26,fc27 #shape = [7,batch_size,65]
  159. # 卷积神经网络返回的输出层,进行交叉熵计算
  160. def losses(logits1,logits2,logits3,logits4,logits5,logits6,logits7,labels):
  161. '''Compute loss from logits and labels
  162. Args:
  163. logits: logits tensor, float, [7*batch_size, 65]
  164. labels: label tensor, tf.int32, [7*batch_size]
  165. Returns:
  166. loss tensor of float type
  167. '''
  168. labels = tf.convert_to_tensor(labels,tf.int32)
  169. with tf.variable_scope('loss1') as scope:
  170. cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits1, labels=labels[:,0], name='xentropy_per_example')
  171. #cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits,labels=labels,name='xentropy_per_example')
  172. loss1 = tf.reduce_mean(cross_entropy, name='loss1')
  173. tf.summary.scalar(scope.name+'/loss1', loss1)
  174. with tf.variable_scope('loss2') as scope:
  175. cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits2, labels=labels[:,1], name='xentropy_per_example')
  176. #cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits,labels=labels,name='xentropy_per_example')
  177. loss2 = tf.reduce_mean(cross_entropy, name='loss2')
  178. tf.summary.scalar(scope.name+'/loss2', loss2)
  179. with tf.variable_scope('loss3') as scope:
  180. cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits3, labels=labels[:,2], name='xentropy_per_example')
  181. #cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits,labels=labels,name='xentropy_per_example')
  182. loss3 = tf.reduce_mean(cross_entropy, name='loss3')
  183. tf.summary.scalar(scope.name+'/loss3', loss3)
  184. with tf.variable_scope('loss4') as scope:
  185. cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits4, labels=labels[:,3], name='xentropy_per_example')
  186. #cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits,labels=labels,name='xentropy_per_example')
  187. loss4 = tf.reduce_mean(cross_entropy, name='loss4')
  188. tf.summary.scalar(scope.name+'/loss4', loss4)
  189. with tf.variable_scope('loss5') as scope:
  190. cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits5, labels=labels[:,4], name='xentropy_per_example')
  191. #cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits,labels=labels,name='xentropy_per_example')
  192. loss5 = tf.reduce_mean(cross_entropy, name='loss5')
  193. tf.summary.scalar(scope.name+'/loss5', loss5)
  194. with tf.variable_scope('loss6') as scope:
  195. cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits6, labels=labels[:,5], name='xentropy_per_example')
  196. #cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits,labels=labels,name='xentropy_per_example')
  197. loss6 = tf.reduce_mean(cross_entropy, name='loss6')
  198. tf.summary.scalar(scope.name+'/loss6', loss6)
  199. with tf.variable_scope('loss7') as scope:
  200. cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits7, labels=labels[:,6], name='xentropy_per_example')
  201. #cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits,labels=labels,name='xentropy_per_example')
  202. loss7 = tf.reduce_mean(cross_entropy, name='loss7')
  203. tf.summary.scalar(scope.name+'/loss7', loss7)
  204. return loss1,loss2,loss3,loss4,loss5,loss6,loss7
  205. # 最优化,自适应梯度下降,进行优化
  206. def trainning( loss1,loss2,loss3,loss4,loss5,loss6,loss7, learning_rate):
  207. '''Training ops, the Op returned by this function is what must be passed to
  208. 'sess.run()' call to cause the model to train.
  209. Args:
  210. loss: loss tensor, from losses()
  211. Returns:
  212. train_op: The op for trainning
  213. '''
  214. with tf.name_scope('optimizer1'):
  215. optimizer1 = tf.train.AdamOptimizer(learning_rate= learning_rate)
  216. global_step = tf.Variable(0, name='global_step', trainable=False)
  217. train_op1 = optimizer1.minimize(loss1, global_step= global_step)
  218. with tf.name_scope('optimizer2'):
  219. optimizer2 = tf.train.AdamOptimizer(learning_rate= learning_rate)
  220. global_step = tf.Variable(0, name='global_step', trainable=False)
  221. train_op2 = optimizer2.minimize(loss2, global_step= global_step)
  222. with tf.name_scope('optimizer3'):
  223. optimizer3 = tf.train.AdamOptimizer(learning_rate= learning_rate)
  224. global_step = tf.Variable(0, name='global_step', trainable=False)
  225. train_op3 = optimizer3.minimize(loss3, global_step= global_step)
  226. with tf.name_scope('optimizer4'):
  227. optimizer4 = tf.train.AdamOptimizer(learning_rate= learning_rate)
  228. global_step = tf.Variable(0, name='global_step', trainable=False)
  229. train_op4 = optimizer4.minimize(loss4, global_step= global_step)
  230. with tf.name_scope('optimizer5'):
  231. optimizer5 = tf.train.AdamOptimizer(learning_rate= learning_rate)
  232. global_step = tf.Variable(0, name='global_step', trainable=False)
  233. train_op5 = optimizer5.minimize(loss5, global_step= global_step)
  234. with tf.name_scope('optimizer6'):
  235. optimizer6 = tf.train.AdamOptimizer(learning_rate= learning_rate)
  236. global_step = tf.Variable(0, name='global_step', trainable=False)
  237. train_op6 = optimizer6.minimize(loss6, global_step= global_step)
  238. with tf.name_scope('optimizer7'):
  239. optimizer7 = tf.train.AdamOptimizer(learning_rate= learning_rate)
  240. global_step = tf.Variable(0, name='global_step', trainable=False)
  241. train_op7 = optimizer7.minimize(loss7, global_step= global_step)
  242. return train_op1,train_op2,train_op3,train_op4,train_op5,train_op6,train_op7
  243. # 对模型评估
  244. def evaluation(logits1,logits2,logits3,logits4,logits5,logits6,logits7,labels):
  245. """Evaluate the quality of the logits at predicting the label.
  246. Args:
  247. logits: Logits tensor, float - [batch_size, NUM_CLASSES].
  248. labels: Labels tensor, int32 - [batch_size], with values in the
  249. range [0, NUM_CLASSES).
  250. Returns:
  251. A scalar int32 tensor with the number of examples (out of batch_size)
  252. that were predicted correctly.
  253. """
  254. logits_all = tf.concat([logits1,logits2,logits3,logits4,logits5,logits6,logits7],0)
  255. labels = tf.convert_to_tensor(labels,tf.int32)
  256. labels_all = tf.reshape(tf.transpose(labels),[-1])
  257. with tf.variable_scope('accuracy') as scope:
  258. correct = tf.nn.in_top_k(logits_all, labels_all, 1)
  259. correct = tf.cast(correct, tf.float16)
  260. accuracy = tf.reduce_mean(correct)
  261. tf.summary.scalar(scope.name+'/accuracy', accuracy)
  262. return accuracy

训练模型:train.py

  1. import os
  2. import numpy as np
  3. import tensorflow as tf
  4. from input_data import OCRIter
  5. import model
  6. import time
  7. import datetime
  8. # train训练
  9. img_w = 272
  10. img_h = 72
  11. num_label=7
  12. batch_size = 8
  13. # count =30000
  14. count = 500000
  15. learning_rate = 0.0001
  16. #默认参数[N,H,W,C]
  17. image_holder = tf.placeholder(tf.float32,[batch_size,img_h,img_w,3])
  18. label_holder = tf.placeholder(tf.int32,[batch_size,7])
  19. keep_prob = tf.placeholder(tf.float32)
  20. logs_train_dir = r'H:\GPpython\第三阶段数据分析\神经网络\Licence_plate_recognize\Licence_plate_recognize\train_result'
  21. def get_batch():
  22. data_batch = OCRIter(batch_size,img_h,img_w)
  23. image_batch,label_batch = data_batch.iter()
  24. image_batch1 = np.array(image_batch)
  25. label_batch1 = np.array(label_batch)
  26. return image_batch1,label_batch1
  27. def fit():
  28. train_logits1, train_logits2, train_logits3, train_logits4, train_logits5, train_logits6, train_logits7 = model.inference(
  29. image_holder, keep_prob)
  30. train_loss1, train_loss2, train_loss3, train_loss4, train_loss5, train_loss6, train_loss7 = model.losses(
  31. train_logits1, train_logits2, train_logits3, train_logits4, train_logits5, train_logits6, train_logits7,
  32. label_holder)
  33. train_op1, train_op2, train_op3, train_op4, train_op5, train_op6, train_op7 = model.trainning(train_loss1,
  34. train_loss2,
  35. train_loss3,
  36. train_loss4,
  37. train_loss5,
  38. train_loss6,
  39. train_loss7,
  40. learning_rate)
  41. train_acc = model.evaluation(train_logits1, train_logits2, train_logits3, train_logits4, train_logits5,
  42. train_logits6, train_logits7, label_holder)
  43. input_image = tf.summary.image('input', image_holder)
  44. summary_op = tf.summary.merge(tf.get_collection(tf.GraphKeys.SUMMARIES))
  45. sess = tf.Session()
  46. train_writer = tf.summary.FileWriter(logs_train_dir, sess.graph)
  47. saver = tf.train.Saver()
  48. sess.run(tf.global_variables_initializer())
  49. start_time1 = time.time()
  50. for step in range(count):
  51. x_batch, y_batch = get_batch()
  52. start_time2 = time.time()
  53. time_str = datetime.datetime.now().isoformat()
  54. feed_dict = {image_holder: x_batch, label_holder: y_batch, keep_prob: 0.5}
  55. _, _, _, _, _, _, _, tra_loss1, tra_loss2, tra_loss3, tra_loss4, tra_loss5, tra_loss6, tra_loss7, acc, summary_str = sess.run(
  56. [train_op1, train_op2, train_op3, train_op4, train_op5, train_op6, train_op7, train_loss1, train_loss2,
  57. train_loss3, train_loss4, train_loss5, train_loss6, train_loss7, train_acc, summary_op], feed_dict)
  58. train_writer.add_summary(summary_str, step)
  59. duration = time.time() - start_time2
  60. tra_all_loss = tra_loss1 + tra_loss2 + tra_loss3 + tra_loss4 + tra_loss5 + tra_loss6 + tra_loss7
  61. # print(y_batch) #仅测试代码训练实际样本与标签是否一致
  62. if step % 10 == 0:
  63. sec_per_batch = float(duration)
  64. print('%s : Step %d,train_loss = %.2f,acc= %.2f,sec/batch=%.3f' % (
  65. time_str, step, tra_all_loss, acc, sec_per_batch))
  66. if step % 10000 == 0 or (step + 1) == count:
  67. checkpoint_path = os.path.join(logs_train_dir, 'model.ckpt')
  68. saver.save(sess, checkpoint_path, global_step=step)
  69. sess.close()
  70. print(time.time() - start_time1)
  71. if __name__ == '__main__':
  72. # fit()
  73. data,labels = get_batch()
  74. print(data.shape)
  75. print(labels.shape)
  76. print(labels[0])

除了输出层使用ReLU激活函数之外,所有层都采用深度神经网络的标准结构。指示存在的节点使用sigmoid激活函数,典型地用于二值输出。其他输出节点使用softmax贯穿字符(结果是每一列的概率之和为1),是模型化离散概率分布的标准方法。

根据标签和网络输出的交叉熵来定义损失函数。为了数值稳定性,利用softmax_cross_entropy_with_logitssigmoid_cross_entropy_with_logits将最后一层的激活函数卷入交叉熵的计算。关于对交叉熵详细而直观的介绍可以参考Michael A. Nielsen的free online book中查看这一节

使用一块nVidia GTX 960m花费大约数小时来训练(train.py),通过CPU的一个后台进程来运行训练数据的生成。

输出处理

 

 

  1. import tensorflow as tf
  2. import numpy as np
  3. import os
  4. from PIL import Image
  5. import cv2
  6. import matplotlib.pyplot as plt
  7. import model
  8. import genplate
  9. index = {"京": 0, "沪": 1, "津": 2, "渝": 3, "冀": 4, "晋": 5, "蒙": 6, "辽": 7, "吉": 8, "黑": 9, "苏": 10, "浙": 11, "皖": 12,
  10. "闽": 13, "赣": 14, "鲁": 15, "豫": 16, "鄂": 17, "湘": 18, "粤": 19, "桂": 20, "琼": 21, "川": 22, "贵": 23, "云": 24,
  11. "藏": 25, "陕": 26, "甘": 27, "青": 28, "宁": 29, "新": 30, "0": 31, "1": 32, "2": 33, "3": 34, "4": 35, "5": 36,
  12. "6": 37, "7": 38, "8": 39, "9": 40, "A": 41, "B": 42, "C": 43, "D": 44, "E": 45, "F": 46, "G": 47, "H": 48,
  13. "J": 49, "K": 50, "L": 51, "M": 52, "N": 53, "P": 54, "Q": 55, "R": 56, "S": 57, "T": 58, "U": 59, "V": 60,
  14. "W": 61, "X": 62, "Y": 63, "Z": 64};
  15. chars = ["京", "沪", "津", "渝", "冀", "晋", "蒙", "辽", "吉", "黑", "苏", "浙", "皖", "闽", "赣", "鲁", "豫", "鄂", "湘", "粤", "桂",
  16. "琼", "川", "贵", "云", "藏", "陕", "甘", "青", "宁", "新", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A",
  17. "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X",
  18. "Y", "Z"
  19. ];
  20. '''
  21. Test one image against the saved models and parameters
  22. '''
  23. global pic
  24. def get_one_image(test):
  25. '''
  26. Randomly pick one image from training data
  27. Return: ndarry
  28. '''
  29. G = genplate.GenPlate("./font/platech.ttf", './font/platechar.ttf', "./NoPlates")
  30. G.genBatch(15, 2, range(31, 65), "./plate", (272, 72)) # 注释原因为每次其他模块运行,若导入该库,都会刷性该函数
  31. n = len(test)
  32. ind =np.random.randint(0,n)
  33. img_dir = test[ind]
  34. image_show = Image.open(img_dir)
  35. plt.imshow(image_show)
  36. #image = image.resize([120,30])
  37. image = cv2.imread(img_dir)
  38. global pic
  39. pic = image
  40. # cv2.imshow('image', image)
  41. # cv2.waitKey(0)
  42. img = np.multiply(image,1/255.0)
  43. #image = np.array(img)
  44. #image = img.transpose(1,0,2)
  45. image = np.array([img])
  46. print(image.shape)
  47. return image
  48. batch_size = 1
  49. x = tf.placeholder(tf.float32,[batch_size,72,272,3])
  50. keep_prob =tf.placeholder(tf.float32)
  51. test_dir = r'H:/GPpython/Licence_plate_recognize/plate/'
  52. test_image = []
  53. for file in os.listdir(test_dir):
  54. test_image.append(test_dir + file)
  55. test_image = list(test_image)
  56. image_array = get_one_image(test_image)
  57. #logit = model.inference(x,keep_prob)
  58. logit1,logit2,logit3,logit4,logit5,logit6,logit7 = model.inference(x,keep_prob)
  59. #logit1 = tf.nn.softmax(logit1)
  60. #logit2 = tf.nn.softmax(logit2)
  61. #logit3 = tf.nn.softmax(logit3)
  62. #logit4 = tf.nn.softmax(logit4)
  63. #logit5 = tf.nn.softmax(logit5)
  64. #logit6 = tf.nn.softmax(logit6)
  65. #logit7 = tf.nn.softmax(logit7)
  66. logs_train_dir = r'H:/GPpython/Licence_plate_recognize/train_result/'
  67. saver = tf.train.Saver()
  68. with tf.Session() as sess:
  69. print ("Reading checkpoint...")
  70. ckpt = tf.train.get_checkpoint_state(logs_train_dir)
  71. if ckpt and ckpt.model_checkpoint_path:
  72. global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]
  73. saver.restore(sess, ckpt.model_checkpoint_path)
  74. print('Loading success, global_step is %s' % global_step)
  75. else:
  76. print('No checkpoint file found')
  77. pre1,pre2,pre3,pre4,pre5,pre6,pre7 = sess.run([logit1,logit2,logit3,logit4,logit5,logit6,logit7], feed_dict={x: image_array,keep_prob:1.0})
  78. prediction = np.reshape(np.array([pre1,pre2,pre3,pre4,pre5,pre6,pre7]),[-1,65])
  79. #prediction = np.array([[pre1],[pre2],[pre3],[pre4],[pre5],[pre6],[pre7]])
  80. #print(prediction)
  81. max_index = np.argmax(prediction,axis=1)
  82. print(max_index)
  83. line = ''
  84. for i in range(prediction.shape[0]):
  85. if i == 0:
  86. result = np.argmax(prediction[i][0:31])
  87. if i == 1:
  88. result = np.argmax(prediction[i][41:65])+41
  89. if i > 1:
  90. result = np.argmax(prediction[i][31:65])+31
  91. line += chars[result]+" "
  92. print ('predicted: ' + line)
  93. cv2.imshow('pic',pic)
  94. cv2.waitKeyEx(0)

总结

我已经开源了一个拥有相对较短代码系统,它不用导入任何特定领域的库以及不需要太多特定领域的知识,就能够实现车牌号自动识别。此外,我还通过在线合成图片的方法解决了上千张训练图片的需求问题(通常是在深度神经网络的情况下)。

另一方面,我的系统也存在一些缺点

  1. 只适用于特定车牌号。尤其是,网络结构明确假定了输出只有7个字符。
  2. 只适用于特定字体。
  3. 速度太慢。该系统运行一张适当尺寸的图片要花费几秒钟。

为了解决第1个问题,谷歌团队将他们的网络结构的高层拆分成了多个子网络,每一个子网络用于假定输出号码中的不同号码位。还有一个并行的子网络来决定存在多少号码。我觉得这种方法可以应用到这儿,但是我没有在这个项目中实现。

关于第2点我在上面举过例子,由于字体的稍微不同只能使用于国内车牌。如果尝试着检测US车牌号的话,误检将会更加严重,因为US车牌号字体类型更多。一个可能的解决方案就是使得训练数据有更多不同的字体类型可选择,尽管还不清楚需要多少字体类型才能成功。

第3点提到的速度慢的问题是扼杀许多应用的cancer:在一个相当强大的GPU上处理一张适当尺寸的输入图片就要花费几秒钟。我认为不引进一种级联式结构的检测网络就想避开这个问题是不太可能的,比如Haar级联,HOG检测器,或者一个更简单的神经网络。

我很有兴趣去尝试和其他机器学习方法的比较会怎样,特别是姿态回归看起来有希望,最后可能会附加一个最基本的分类阶段。如果使用了像scikit-learn这样的机器学习库,那么应该同样简单。

版权声明:如无特殊说明,文章均为本站原创,转载请注明出处

本文链接:http://wakemeupnow.cn/article/car/