文章目录

  • 序言
  • 识别方案
    • 方案1
    • 方案2
    • 选择方案:
  • 准备数据
    • 数据的准备
    • 读取数据集
    • 构建神经网络
    • 进行训练
    • 查看模型的准确度
    • 优化
    • 测试效果
  • 进行车牌字符预测
    • 实测
    • 总结
    • 下一章
  • 完整代码:
    • 数据处理
    • 神经网络
    • 训练
    • 查看效果
    • 预测方法
    • 运行

序言

  • 上篇文章中,我们实现了简单的车牌提取功能,并分成了多个图片保存在本地上,接下来,我们要进行车牌字符的识别。
  • 车牌的文字如下:

识别方案

  • 有两种识别字符的方案

方案1

  • 运用模板匹配,opencv自带的template进行匹配。
  • 缺点:对特殊的字符样式可能无法识别,只能识别较为规则的字符
  • 优点: 不需要太多的特征数据集即可识别大部分字符

方案2

  • 运用卷积神经网络训练一个神经系统进行识别
  • 缺点: 需要大量的训练数据, 对训练数据要求较高
  • 优点: 能识别各种不标准的车牌特征

选择方案:

  • 本文中将以第二种方案进行识别

准备数据

数据集下载

  • 为大家准备好了数据集,分为两种格式。


  • 第二种是以不同背景和数字颜色组成的

  • 大家可根据项目需求进行选择,这里我选的是第一种黑白图的数据集进行训练的。

数据的准备

读取数据集

  • 数据较少, 所以需要做一些变换,增加泛化。
# 读取文件
from keras.preprocessing.image import ImageDataGeneratortrain_gen = ImageDataGenerator(rescale=1/255.0, horizontal_flip=True, rotation_range=30, vertical_flip=True, featurewise_center=True, width_shift_range=12, height_shift_range=12)
valid_gen = ImageDataGenerator(rescale=1/255.0, horizontal_flip=True, rotation_range=30, vertical_flip=True, featurewise_center=True, width_shift_range=12, height_shift_range=12)
test_gen = ImageDataGenerator(rescale= 1/ 255.0)train_img_gen = train_gen.flow_from_directory('./tf_car_license_dataset/train_images/training-set/', target_size=(32, 32), batch_size=32, color_mode='grayscale')
valid_img_gen = train_gen.flow_from_directory('./tf_car_license_dataset/train_images/validation-set/', target_size=(32, 32), batch_size=32, color_mode='grayscale')

  • 一共有四十个类目

构建神经网络

  • 这里运用了两层的卷积神经网络,并进行两次池化操作,最后用全连接层进行分类,优化函数选择adam 损失函数用交叉熵损失函数。
- 这里
# 构建神经网络
model = keras.Sequential([keras.layers.Conv2D(32, (3, 3), 1, padding='same', activation="relu", input_shape = (32, 32, 1)),keras.layers.MaxPool2D(2, 2),keras.layers.Conv2D(64, (3, 3), 1, activation='relu'),keras.layers.MaxPool2D(2, 2),keras.layers.Flatten(),keras.layers.Dense(128, activation='relu'),keras.layers.Dense(40, activation='softmax')
])
model.compile(optimizer='adam', loss = keras.losses.categorical_crossentropy, metrics=['acc'])
model.summary()

进行训练

history = model.fit(train_img_gen, validation_data = valid_img_gen, epochs=30, batch_size=128)

查看模型的准确度

import matplotlib.pyplot as plt
losses = history.history['loss']
val_losses = history.history['val_loss']
acc = history.history['acc']
val_acc = history.history['val_acc']
plt.figure(figsize=(12, 6))
plt.subplot(121)
plt.xlabel('fit_nums')
plt.ylabel('losses')
plt.plot(losses,'b-')
plt.plot(val_losses,'b--')
plt.subplot(122)
plt.xlabel('fit_nums')
plt.ylabel('acc')
plt.plot(acc, 'b-', label='acc')
plt.plot(val_acc, 'b--', label = 'val_acc')
plt.legend()
plt.show()
history.history


可以看到, 训练的效果在不断增强,不过准确率不是很好,还有过拟合的风险,后面优化下。

优化

增加了一下训练次数, 可以看到效果增强了点,

  • 实验下预测效果。

测试效果

运用PIL的Image

from PIL import Imageimg = Image.open('./tf_car_license_dataset/test_images/1.bmp')
img = img.resize((32, 32))
# 这里变成输入的格式(count, size,size, 层数)
img_arr = np.array(img).reshape((1, 32, 32, 1))

注意: 因为我们训练时输入的是灰度图像,没有三通道的,所以之前的图片需要特殊处理成灰度图在进行输入

model.predict(img_arr)


可以看到,这里输出了,one-hot的编码数组,接下来只需要取最大值就可以了

template = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z','京','闽','粤','苏','沪','浙']
template[np.argmax(model.predict(img_arr))]

‘闽’

  • 查看相应的预测效果

进行车牌字符预测

def test_img(path):img = Image.open(path).convert("L")img = img.resize((32, 32))img_arr = np.array(img).reshape((1, 32, 32, 1))template = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z','京','闽','粤','苏','沪','浙']return template[np.argmax(model.predict(img_arr))]# return model.predict(img_arr)

这里直接返回预测的字符

实测

import os
out = ""
for path in os.listdir('./split/'):out += test_img('./split/' + path)print(out)


  • 可以看到预测效果不太好

总结

  • 测试效果不怎么好,数据集太少了,无法拟合不同的图片,接下来进行神经网络优化,提升下泛化能力。
  • 如果有更多的数据集,我们可以训练出精度很高的神经网络,但基本的实现思路就是这样子,

下一章

接下来我将用模板匹配的方式进行效果预测,看看会不会有更好的结果

完整代码:

数据处理

import tensorflow.keras as keras
import numpy as np
# 读取文件
from keras.preprocessing.image import ImageDataGeneratortrain_gen = ImageDataGenerator(rescale=1/255.0, horizontal_flip=True, rotation_range=30, vertical_flip=True, featurewise_center=True, width_shift_range=12, height_shift_range=12)
valid_gen = ImageDataGenerator(rescale=1/255.0, horizontal_flip=True, rotation_range=30, vertical_flip=True, featurewise_center=True, width_shift_range=12, height_shift_range=12)
test_gen = ImageDataGenerator(rescale= 1/ 255.0)train_img_gen = train_gen.flow_from_directory('./tf_car_license_dataset/train_images/training-set/', target_size=(32, 32), batch_size=32, color_mode='grayscale')
valid_img_gen = train_gen.flow_from_directory('./tf_car_license_dataset/train_images/validation-set/', target_size=(32, 32), batch_size=32, color_mode='grayscale')

神经网络

# 构建神经网络
model = keras.Sequential([keras.layers.Conv2D(32, (3, 3), 1, padding='same', activation="relu", input_shape = (32, 32, 1)),keras.layers.MaxPool2D(2, 2),keras.layers.Conv2D(64, (3, 3), 1, activation='relu'),keras.layers.MaxPool2D(2, 2),keras.layers.Flatten(),keras.layers.Dense(128, activation='relu'),keras.layers.Dense(40, activation='softmax')
])
model.compile(optimizer='adam', loss = keras.losses.categorical_crossentropy, metrics=['acc'])
model.summary()

训练

history = model.fit(train_img_gen, validation_data = valid_img_gen, epochs=30, batch_size=128)

查看效果

import matplotlib.pyplot as plt
losses = history.history['loss']
val_losses = history.history['val_loss']
acc = history.history['acc']
val_acc = history.history['val_acc']
plt.figure(figsize=(12, 6))
plt.subplot(121)
plt.xlabel('fit_nums')
plt.ylabel('losses')
plt.plot(losses,'b-')
plt.plot(val_losses,'b--')
plt.subplot(122)
plt.xlabel('fit_nums')
plt.ylabel('acc')
plt.plot(acc, 'b-', label='acc')
plt.plot(val_acc, 'b--', label = 'val_acc')
plt.legend()
plt.show()
history.history

预测方法

def test_img(path):img = Image.open(path).convert("L")img = img.resize((32, 32))img_arr = np.array(img).reshape((1, 32, 32, 1))template = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z','京','闽','粤','苏','沪','浙']return template[np.argmax(model.predict(img_arr))]# return model.predict(img_arr)

运行

import os
out = ""
for path in os.listdir('./split/'):out += test_img('./split/' + path)print(out)

基于CNN 对车牌数字进行识别,(二)相关推荐

  1. 基于CNN的四位数字验证码识别

    前言 验证码技术作为一种反自动化技术,使得很多程序的自动化工作止步.今天作者采用一些数字图像处理和CNN方法来识别较为简单的数字验证码 实验步骤 实验步骤主要围绕以下展开 图像预处理即滤除噪声和字符分 ...

  2. 基于CNN的性别、年龄识别及Demo实现

    一.相关理论 本篇博文主要讲解2015年一篇paper<Age and Gender Classification using Convolutional Neural Networks> ...

  3. 【智能算法】基于CNN算法深度学习车辆识别

    目录 1.基于CNN算法深度学习车辆识别 2.文件准备 3.结果展示 1.基于CNN算法深度学习车辆识别 // The contents of this file are in the public ...

  4. 基于Python的车牌检测和识别系统

    向AI转型的程序员都关注了这个号???????????? 人工智能大数据与深度学习  公众号:datayx 1.车牌检测和识别项目介绍 车牌的检测和识别的应用非常广泛,比如交通违章车牌追踪,小区或地下 ...

  5. Android基于卷积神经网络的数字手势识别识别数字手势0-10 Android studio编译

    这篇博客主要基于我做的一个数字手势识别APP,具体分享下如何一步步训练一个卷积神经网络模型(CNN)模型,然后把模型集成到Android Studio中,开发一个数字手势识别APP.Android基于 ...

  6. 基于MATLAB的车牌定位和识别

    %function carreco clc; clear all; %========================================================== %说明: % ...

  7. 基于 YOLO 的车牌检测与识别

    点击上方"小白学视觉",选择加"星标"或"置顶" 重磅干货,第一时间送达 导读 本文将重点介绍 ALPR 的端到端实现.它将侧重于两个过程: ...

  8. 基于Python的KNN数字验证码识别

    一.主要内容 本项目基于Python爬虫爬取验证码图片,对图片进行去噪.分割,通过KNN算法训练模型,实现验证其准确率. 二.系统流程 首先从指定的网页中爬取验证码图片数据,然后对数据进行一个去噪和分 ...

  9. 深度学习(十四)基于CNN的性别、年龄识别

    CNN应用之性别.年龄识别 原文地址:http://blog.csdn.net/hjimce/article/details/49255013 作者:hjimce 一.相关理论 本篇博文主要讲解201 ...

最新文章

  1. 几则与西门子相关的消息
  2. 年底了,没啥好送的,送个1T移动硬盘吧~
  3. 锁Lock 那点事儿
  4. 数据结构--双向链表
  5. 动态规划训练25 [Food Delivery ZOJ - 3469 ]好题
  6. Mongodb系列- java客户端简单使用(CRUD)
  7. 关于get_magic_quotes_gpc()函数
  8. java中char和string的区别是什么
  9. 强化学习组队学习task05—— 稀疏奖励及模仿学习
  10. c#中,如何获取日期型字段里的年、月、日?
  11. [HCNA] 静态路由配置实例
  12. 第十二章 比较器(1.5)
  13. Kafka的运维利器-AdminClient
  14. 有什么软件可以自动把PDF文件翻译成英文的吗?
  15. android里qq登录界面,Android仿QQ登陆窗口实现原理
  16. python+opencv车道线,实线虚线的检测
  17. 雅思作文未来计算机的应用,雅思写作大作文范文 雅思写作讨论双方观点 人工智能artificial intelligence...
  18. 什么是GoogleNet?什么是Inception?GoogleNet结构详解(2014年)
  19. 南大通用数据库-Gbase-8a-学习-12-Gbase8a常用运维命令(持续更新哈)
  20. 制作学术海报之工具篇

热门文章

  1. Rancher 中应用、服务、容器的概念
  2. nacos启动报错解决方法
  3. windows--花里胡哨的文件图标
  4. Cisco Packet Trancer中小型校园网/企业网/园区网网络设计规划/无线网络
  5. 无插件纯Web HTML5 3D机房 进阶篇(新增设备、线缆、巡查等功能)
  6. 解决:Parameter number 5 is not an OUT parameter
  7. 全面解析四大主流音频技术
  8. 关于高精度交流恒流源设计是怎样的?
  9. Python——飞机大战(day10)
  10. 验证码、通知短信API常见使用问题