生活中车牌识别已经随处可见,那么,大家想知道车牌识别通过深度学习该如何实现嘛?现在,让我们通过百度飞桨paddlepaddle来实现一下吧
环境:paddlepaddle 1.7.0(用到动态图)
数据集: 百度ai数据集 车牌数据
推荐:白嫖百度ai V100显卡的算力(有一说一确实舒服)
因为我们使用的是百度AI的环境,我们先对挂载的数据集进行解压缩
!rm -rf __MACOSX
!unzip -q /home/aistudio/data/data23617/characterData.zip
接下来我们导入需要的库
import numpy as np
import paddle as paddle
import paddle.fluid as fluid
from PIL import Image
import cv2
import matplotlib.pyplot as plt
import os
from multiprocessing import cpu_count
from paddle.fluid.dygraph import Pool2D,Conv2D
# from paddle.fluid.dygraph import FC
from paddle.fluid.dygraph import Linear
其中我们可以看到
from paddle.fluid.dygraph import FC被注释掉了
这是因为在paddlepaddle1.7.0中,动态图的FC被Linear所取代
至于如果使用静态图实现,则无所谓
这里笔者多嘴一句个人感受,静态图使用起来导入数据方便,使用静态图也没有什么大碍,动态图调试起来方便,静态图和动态图之间各位仁者见仁智者见智就行
我们生成对应标签和图像地址的图像列表文件
# 生成车牌字符图像列表
data_path = '/home/aistudio/data'
character_folders = os.listdir(data_path)
label = 0
LABEL_temp = {}
if(os.path.exists('./train_data.list')):
os.remove('./train_data.list')
if(os.path.exists('./test_data.list')):
os.remove('./test_data.list')
for character_folder in character_folders:
with open('./train_data.list', 'a') as f_train:
with open('./test_data.list', 'a') as f_test:
if character_folder == '.DS_Store' or character_folder == '.ipynb_checkpoints' or character_folder == 'data23617':
continue
print(character_folder + " " + str(label))
LABEL_temp[str(label)] = character_folder #存储一下标签的对应关系
character_imgs = os.listdir(os.path.join(data_path, character_folder))
for i in range(len(character_imgs)):
if i%10 == 0:
f_test.write(os.path.join(os.path.join(data_path, character_folder), character_imgs[i]) + "\t" + str(label) + '\n')
else:
f_train.write(os.path.join(os.path.join(data_path, character_folder), character_imgs[i]) + "\t" + str(label) + '\n')
label = label + 1
print('图像列表已生成')
定义一下数据reader
# 用上一步生成的图像列表定义车牌字符训练集和测试集的reader
def data_mapper(sample):
img, label = sample
img = paddle.dataset.image.load_image(file=img, is_color=False)
img = img.flatten().astype('float32') / 255.0
return img, label
def data_reader(data_list_path):
def reader():
with open(data_list_path, 'r') as f:
lines = f.readlines()
for line in lines:
img, label = line.split('\t')
yield img, int(label)
return paddle.reader.xmap_readers(data_mapper, reader, cpu_count(), 1024)
这里对图像进行了归一化和扁平化
注意的是,paddle的load_image好像是封装opencv的imread实现,众所周知,opencv对window的支持有些毛病,所以尽量在本地跑的小伙伴注意,图像所在位置或路径中不要有中文
定义数据提供器,选择乱序,批大小为128张图
# 用于训练的数据提供器
train_reader = paddle.batch(reader=paddle.reader.shuffle(reader=data_reader('./train_data.list'), buf_size=512), batch_size=128)
# 用于测试的数据提供器
test_reader = paddle.batch(reader=data_reader('./test_data.list'), batch_size=128)
#定义网络
class MyLeNet(fluid.dygraph.Layer):
def __init__(self, training): # 输入128,1,20,20
super(MyLeNet,self).__init__()
self.hidden1_1 = Conv2D(num_channels=1, num_filters=32, filter_size=3, act='relu') # 128 32 18 18
self.hidden1_2 = Pool2D(pool_size=2, pool_stride=2) # 9 9
self.hidden2_1 = Conv2D(num_channels=32, num_filters=32, filter_size=3, act='relu') # 128 32 7 7
self.hidden2_2 = Pool2D(pool_size=2, pool_stride=2) # 3 3
self.hidden3 = Conv2D(num_channels=32, num_filters=64, filter_size=3, act='relu') # 128 64 1 1
self.hidden4 = Linear(input_dim=64, output_dim=512, act='relu')
self.drop_ratiol = 0.5 if training else 0.0
self.hidden5 = Linear(input_dim=512, output_dim=65, act='relu')
def forward(self,inputs):
conv1 = self.hidden1_1(inputs)
pool1 = self.hidden1_2(conv1)
conv2 = self.hidden2_1(pool1)
pool2 = self.hidden2_2(conv2)
conv3 = self.hidden3(pool2)
rs_1 = fluid.layers.reshape(conv3, [conv3.shape[0], -1])
fc1 = self.hidden4(rs_1)
drop1 = fluid.layers.dropout(fc1, self.drop_ratiol)#, is_test=is_test)
y = self.hidden5(drop1)
return y
在进行将图像拉平的过程中
使用
x = fluid.layers.flatten(x)
和使用
rs_1 = fluid.layers.reshape(conv3, [conv3.shape[0], -1])
是一样的
笔者其实在此时也是刚刚接触paddlepaddle,所以对框架中的api有些陌生
同样的
self.drop_ratiol = 0.5 if training else 0.0
完全可以换成
drop1 = fluid.layers.dropout(fc1, self.drop_ratiol, is_test=is_test)
这样
将初始化中的training换成is_test即可
place = fluid.CPUPlace()
with fluid.dygraph.guard(place):
model=MyLeNet(True) #模型实例化
model.train() #训练模式
#opt=fluid.optimizer.SGDOptimizer(learning_rate=0.001, parameter_list=model.parameters())#优化器选用SGD随机梯度下降,学习率为0.001.
opt =fluid.optimizer.Momentum(learning_rate=0.001, momentum=0.9, parameter_list=model.parameters())
epochs_num= 50 #迭代次数为2
for pass_num in range(epochs_num):
for batch_id,data in enumerate(train_reader()):
images=np.array([x[0].reshape(1,20,20) for x in data],np.float32)
labels = np.array([x[1] for x in data]).astype('int64')
labels = labels[:, np.newaxis]
image=fluid.dygraph.to_variable(images)
label=fluid.dygraph.to_variable(labels)
logits=model(image)#预测
predict = fluid.layers.softmax(logits)
#loss=fluid.layers.cross_entropy(predict,label)
loss = fluid.layers.softmax_with_cross_entropy(logits, label)
avg_loss=fluid.layers.mean(loss)#获取loss值
acc=fluid.layers.accuracy(predict,label)#计算精度
if batch_id!=0 and batch_id%50==0:
print("train_pass:{},batch_id:{},train_loss:{},train_acc:{}".format(pass_num,batch_id,avg_loss.numpy(),acc.numpy()))
avg_loss.backward()
opt.minimize(avg_loss)
model.clear_gradients()
fluid.save_dygraph(model.state_dict(),'MyLeNet')#保存模型
#模型校验
with fluid.dygraph.guard():
accs = []
model=MyLeNet(False)#模型实例化
model_dict,_=fluid.load_dygraph('MyLeNet')
model.load_dict(model_dict)#加载模型参数
model.eval()#评估模式
for batch_id,data in enumerate(test_reader()):#测试集
images=np.array([x[0].reshape(1,20,20) for x in data],np.float32)
labels = np.array([x[1] for x in data]).astype('int64')
labels = labels[:, np.newaxis]
image=fluid.dygraph.to_variable(images)
label=fluid.dygraph.to_variable(labels)
predict=model(image)#预测
acc=fluid.layers.accuracy(predict,label)
accs.append(acc.numpy()[0])
avg_acc = np.mean(accs)
print(avg_acc)
笔者仅跑了50ep,模型还未到极限
笔者在这仅跑出0.85的准确率,大家可以自行修改调参
在后来的部分,笔者调参跑出了0.96的准确率
例如使用动态的学习率等来提高准确率
对车牌图片进行处理,分割出车牌中的每一个字符并保存
license_plate = cv2.imread('./车牌.png')
gray_plate = cv2.cvtColor(license_plate, cv2.COLOR_RGB2GRAY)
ret, binary_plate = cv2.threshold(gray_plate, 175, 255, cv2.THRESH_BINARY)
result = []
for col in range(binary_plate.shape[1]):
result.append(0)
for row in range(binary_plate.shape[0]):
result[col] = result[col] + binary_plate[row][col]/255
character_dict = {}
num = 0
i = 0
while i < len(result):
if result[i] == 0:
i += 1
else:
index = i + 1
while result[index] != 0:
index += 1
character_dict[num] = [i, index-1]
num += 1
i = index
for i in range(8):
if i==2:
continue
padding = (170 - (character_dict[i][1] - character_dict[i][0])) / 2
ndarray = np.pad(binary_plate[:,character_dict[i][0]:character_dict[i][1]], ((0,0), (int(padding), int(padding))), 'constant', constant_values=(0,0))
ndarray = cv2.resize(ndarray, (20,20))
cv2.imwrite('./' + str(i) + '.png', ndarray)
def load_image(path):
img = paddle.dataset.image.load_image(file=path, is_color=False)
img = img.astype('float32')
img = img[np.newaxis, ] / 255.0
return img
#将标签进行转换
print('Label:',LABEL_temp)
match = {'A':'A','B':'B','C':'C','D':'D','E':'E','F':'F','G':'G','H':'H','I':'I','J':'J','K':'K','L':'L','M':'M','N':'N',
'O':'O','P':'P','Q':'Q','R':'R','S':'S','T':'T','U':'U','V':'V','W':'W','X':'X','Y':'Y','Z':'Z',
'yun':'云','cuan':'川','hei':'黑','zhe':'浙','ning':'宁','jin':'津','gan':'赣','hu':'沪','liao':'辽','jl':'吉','qing':'青','zang':'藏',
'e1':'鄂','meng':'蒙','gan1':'甘','qiong':'琼','shan':'陕','min':'闽','su':'苏','xin':'新','wan':'皖','jing':'京','xiang':'湘','gui':'贵',
'yu1':'渝','yu':'豫','ji':'冀','yue':'粤','gui1':'桂','sx':'晋','lu':'鲁',
'0':'0','1':'1','2':'2','3':'3','4':'4','5':'5','6':'6','7':'7','8':'8','9':'9'}
L = 0
LABEL ={}
for V in LABEL_temp.values():
LABEL[str(L)] = match[V]
L += 1
print(LABEL)
#构建预测动态图过程
with fluid.dygraph.guard():
model=MyLeNet(True)#模型实例化
model_dict,_=fluid.load_dygraph('MyLeNet')
model.load_dict(model_dict)#加载模型参数
model.eval()#评估模式
lab=[]
for i in range(8):
if i==2:
continue
infer_imgs = []
infer_imgs.append(load_image('./' + str(i) + '.png'))
infer_imgs = np.array(infer_imgs)
infer_imgs = fluid.dygraph.to_variable(infer_imgs)
result=model(infer_imgs)
lab.append(np.argmax(result.numpy()))
# print(lab)
display(Image.open('./车牌.png'))
print('\n车牌识别结果为:',end='')
for i in range(len(lab)):
print(LABEL[str(lab[i])],end='')
最终将结果预测出来,是正确的