初学图像处理,做了一个车牌提取项目,本博客仅仅是为了记录一下学习过程,该项目只具备初级功能,还有待改善

第一部分:车牌倾斜矫正

# 导入所需模块
import cv2
import math
from matplotlib import pyplot as plt # 显示图片
def cv_show(name,img):
cv2.imshow(name,img)
cv2.waitKey()
cv2.destroyAllWindows() # 调整图片大小
def resize(image, width=None, height=None, inter=cv2.INTER_AREA):
dim = None
(h, w) = image.shape[:2]
if width is None and height is None:
return image
if width is None:
r = height / float(h)
dim = (int(w * r), height)
else:
r = width / float(w)
dim = (width, int(h * r))
resized = cv2.resize(image, dim, interpolation=inter)
return resized # 加载图片
origin_Image = cv2.imread("./images/car_09.jpg")
rawImage = resize(origin_Image,height=500) # 高斯去噪
image = cv2.GaussianBlur(rawImage, (3, 3), 0)
# 灰度处理
gray_image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
# sobel算子边缘检测(做了一个y方向的检测)
Sobel_x = cv2.Sobel(gray_image, cv2.CV_16S, 1, 0)
absX = cv2.convertScaleAbs(Sobel_x) # 转回uint8
image = absX
# 自适应阈值处理
ret, image = cv2.threshold(image, 0, 255, cv2.THRESH_OTSU)
# 闭运算,是白色部分练成整体
kernelX = cv2.getStructuringElement(cv2.MORPH_RECT, (14, 5))
image = cv2.morphologyEx(image, cv2.MORPH_CLOSE, kernelX,iterations = 1)
# 去除一些小的白点
kernelX = cv2.getStructuringElement(cv2.MORPH_RECT, (20, 1))
kernelY = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 19))
# 膨胀,腐蚀
image = cv2.dilate(image, kernelX)
image = cv2.erode(image, kernelX)
# 腐蚀,膨胀
image = cv2.erode(image, kernelY)
image = cv2.dilate(image, kernelY)
# 中值滤波去除噪点
image = cv2.medianBlur(image, 15)
# 轮廓检测
# cv2.RETR_EXTERNAL表示只检测外轮廓
# cv2.CHAIN_APPROX_SIMPLE压缩水平方向,垂直方向,对角线方向的元素,只保留该方向的终点坐标,例如一个矩形轮廓只需4个点来保存轮廓信息
thresh_, contours, hierarchy = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 绘制轮廓
image1 = rawImage.copy()
cv2.drawContours(image1, contours, -1, (0, 255, 0), 5)
cv_show('image1',image1) # 筛选出车牌位置的轮廓
# 这里我只做了一个车牌的长宽比在3:1到4:1之间这样一个判断
for i,item in enumerate(contours): # enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在for循环当中
# cv2.boundingRect用一个最小的矩形,把找到的形状包起来
rect = cv2.boundingRect(item)
x = rect[0]
y = rect[1]
weight = rect[2]
height = rect[3]
if (weight > (height * 1.5)) and (weight < (height * 4)) and height>50:
index = i
image2 = rawImage.copy()
cv2.drawContours(image2, contours, index, (0, 0, 255), 3)
cv_show('image2',image2)
# 参数:
#  https://blog.csdn.net/lovetaozibaby/article/details/99482973
# InputArray Points: 待拟合的直线的集合,必须是矩阵形式;
# distType: 距离类型。fitline为距离最小化函数,拟合直线时,要使输入点到拟合直线的距离和最小化。这里的 距离的类型有以下几种:
# cv2.DIST_USER : User defined distance
# cv2.DIST_L1: distance = |x1-x2| + |y1-y2|
# cv2.DIST_L2: 欧式距离,此时与最小二乘法相同
# cv2.DIST_C:distance = max(|x1-x2|,|y1-y2|)
# cv2.DIST_L12:L1-L2 metric: distance = 2(sqrt(1+x*x/2) - 1))
# cv2.DIST_FAIR:distance = c^2(|x|/c-log(1+|x|/c)), c = 1.3998
# cv2.DIST_WELSCH: distance = c2/2(1-exp(-(x/c)2)), c = 2.9846
# cv2.DIST_HUBER:distance = |x|<c ? x^2/2 : c(|x|-c/2), c=1.345
# param: 距离参数,跟所选的距离类型有关,值可以设置为0。
#
# reps, aeps: 第5/6个参数用于表示拟合直线所需要的径向和角度精度,通常情况下两个值均被设定为1e-2.
# output :
#
# 对于二维直线,输出output为4维,前两维代表拟合出的直线的方向,后两位代表直线上的一点。(即通常说的点斜式直线)
# 其中(vx, vy) 是直线的方向向量,(x, y) 是直线上的一个点。
# 斜率k = vy / vx
# 截距b = y - k * x # 直线拟合找斜率
cnt = contours[index]
image3 = rawImage.copy()
h, w = image3.shape[:2]
[vx, vy, x, y] = cv2.fitLine(cnt, cv2.DIST_L2, 0, 0.01, 0.01)
k = vy/vx
b = y-k*x
lefty = b
righty = k*w+b
img = cv2.line(image3, (w, righty), (0, lefty), (0, 255, 0), 2)
cv_show('img',img) a = math.atan(k)
a = math.degrees(a)
image4 = origin_Image.copy()
# 图像旋转
h,w = image4.shape[:2]
print(h,w)
#第一个参数旋转中心,第二个参数旋转角度,第三个参数:缩放比例
M = cv2.getRotationMatrix2D((w/2,h/2),a,1)
#第三个参数:变换后的图像大小
dst = cv2.warpAffine(image4,M,(int(w*1),int(h*1)))
cv_show('dst',dst)
cv2.imwrite('car_09.jpg',dst)

第二部分:车牌号码提取

 # 导入所需模块
import cv2
from matplotlib import pyplot as plt
import os
import numpy as np # 显示图片
def cv_show(name,img):
cv2.imshow(name,img)
cv2.waitKey()
cv2.destroyAllWindows() def resize(image, width=None, height=None, inter=cv2.INTER_AREA):
dim = None
(h, w) = image.shape[:2]
if width is None and height is None:
return image
if width is None:
r = height / float(h)
dim = (int(w * r), height)
else:
r = width / float(w)
dim = (width, int(h * r))
resized = cv2.resize(image, dim, interpolation=inter)
return resized #读取待检测图片
origin_image = cv2.imread('./car_09.jpg')
resize_image = resize(origin_image,height=600)
ratio = origin_image.shape[0]/600
print(ratio)
cv_show('resize_image',resize_image) #高斯滤波,灰度化
image = cv2.GaussianBlur(resize_image, (3, 3), 0)
gray_image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
cv_show('gray_image',gray_image) #梯度化
Sobel_x = cv2.Sobel(gray_image, cv2.CV_16S, 1, 0)
absX = cv2.convertScaleAbs(Sobel_x)
image = absX
cv_show('image',image) #闭操作
ret, image = cv2.threshold(image, 0, 255, cv2.THRESH_OTSU)
kernelX = cv2.getStructuringElement(cv2.MORPH_RECT, (15, 1))
image = cv2.morphologyEx(image, cv2.MORPH_CLOSE, kernelX, iterations=2)
cv_show('image',image)
kernelX = cv2.getStructuringElement(cv2.MORPH_RECT, (15, 1))
kernelY = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 1))
image = cv2.dilate(image, kernelX)
image = cv2.erode(image, kernelX)
image = cv2.erode(image, kernelY)
image = cv2.dilate(image, kernelY)
image = cv2.medianBlur(image, 9)
cv_show('image',image) #绘制轮廓
thresh, contours, hierarchy = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print(type(contours))
print(len(contours)) cur_img = resize_image.copy()
cv2.drawContours(cur_img,contours,-1,(0,0,255),3)
cv_show('img',cur_img) for item in contours:
rect = cv2.boundingRect(item)
x = rect[0]
y = rect[1]
weight = rect[2]
height = rect[3]
if (weight > (height * 2.5)) and (weight < (height * 4)):
if height > 40 and height < 80:
image = origin_image[int(y*ratio): int((y + height)*ratio), int(x*ratio) : int((x + weight)*ratio)]
cv_show('image',image)
cv2.imwrite('chepai_09.jpg',image)

第三部分:车牌号码分割:

 # 导入所需模块
import cv2
from matplotlib import pyplot as plt
import os
import numpy as np # 显示图片
def cv_show(name,img):
cv2.imshow(name,img)
cv2.waitKey()
cv2.destroyAllWindows() #车牌灰度化
chepai_image = cv2.imread('chepai_09.jpg')
image = cv2.GaussianBlur(chepai_image, (3, 3), 0)
gray_image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
cv_show('gray_image',gray_image) ret, image = cv2.threshold(gray_image, 0, 255, cv2.THRESH_OTSU)
cv_show('image',image) #计算二值图像黑白点的个数,处理绿牌照问题,让车牌号码始终为白色
area_white = 0
area_black = 0
height, width = image.shape
for i in range(height):
for j in range(width):
if image[i, j] == 255:
area_white += 1
else:
area_black += 1
print(area_black,area_white)
if area_white > area_black:
ret, image = cv2.threshold(image, 0, 255, cv2.THRESH_OTSU | cv2.THRESH_BINARY_INV)
cv_show('image',image) #绘制轮廓
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (20, 5))
image = cv2.dilate(image, kernel)
cv_show('image', image)
thresh, contours, hierarchy = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cur_img = chepai_image.copy()
cv2.drawContours(cur_img,contours,-1,(0,0,255),3)
cv_show('img',cur_img)
words = []
word_images = []
print(len(contours))
for item in contours:
word = []
rect = cv2.boundingRect(item)
x = rect[0]
y = rect[1]
weight = rect[2]
height = rect[3]
word.append(x)
word.append(y)
word.append(weight)
word.append(height)
words.append(word)
words = sorted(words, key=lambda s:s[0], reverse=False)
print(words)
i = 0
for word in words:
if (word[3] > (word[2] * 1)) and (word[3] < (word[2] * 5)):
i = i + 1
splite_image = chepai_image[word[1]:word[1] + word[3], word[0]:word[0] + word[2]]
word_images.append(splite_image) for i, j in enumerate(word_images):
cv_show('word_images[i]',word_images[i])
cv2.imwrite("./chepai_09/0{}.png".format(i),word_images[i])

第四部分:字符匹配:

 # 导入所需模块
import cv2
from matplotlib import pyplot as plt
import os
import numpy as np # 准备模板
template = ['','','','','','','','','','',
'A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z',
'藏','川','鄂','甘','赣','贵','桂','黑','沪','吉','冀','津','晋','京','辽','鲁','蒙','闽','宁',
'青','琼','陕','苏','皖','湘','新','渝','豫','粤','云','浙'] # 显示图片
def cv_show(name,img):
cv2.imshow(name,img)
cv2.waitKey()
cv2.destroyAllWindows() # 读取一个文件夹下的所有图片,输入参数是文件名,返回文件地址列表
def read_directory(directory_name):
referImg_list = []
for filename in os.listdir(directory_name):
referImg_list.append(directory_name + "/" + filename)
return referImg_list # 中文模板列表(只匹配车牌的第一个字符)
def get_chinese_words_list():
chinese_words_list = []
for i in range(34,64):
c_word = read_directory('./refer1/'+ template[i])
chinese_words_list.append(c_word)
return chinese_words_list #英文模板列表(只匹配车牌的第二个字符)
def get_english_words_list():
eng_words_list = []
for i in range(10,34):
e_word = read_directory('./refer1/'+ template[i])
eng_words_list.append(e_word)
return eng_words_list # 英文数字模板列表(匹配车牌后面的字符)
def get_eng_num_words_list():
eng_num_words_list = []
for i in range(0,34):
word = read_directory('./refer1/'+ template[i])
eng_num_words_list.append(word)
return eng_num_words_list #模版匹配
def template_matching(words_list):
if words_list == 'chinese_words_list':
template_words_list = chinese_words_list
first_num = 34
elif words_list == 'english_words_list':
template_words_list = english_words_list
first_num = 10
else:
template_words_list = eng_num_words_list
first_num = 0
best_score = []
for template_word in template_words_list:
score = []
for word in template_word:
template_img = cv2.imdecode(np.fromfile(word, dtype=np.uint8), 1)
template_img = cv2.cvtColor(template_img, cv2.COLOR_RGB2GRAY)
ret, template_img = cv2.threshold(template_img, 0, 255, cv2.THRESH_OTSU)
height, width = template_img.shape
image = image_.copy()
image = cv2.resize(image, (width, height))
result = cv2.matchTemplate(image, template_img, cv2.TM_CCOEFF)
score.append(result[0][0])
best_score.append(max(score))
return template[first_num + best_score.index(max(best_score))] referImg_list = read_directory("chepai_13")
chinese_words_list = get_chinese_words_list()
english_words_list = get_english_words_list()
eng_num_words_list = get_eng_num_words_list()
chepai_num = [] #匹配第一个汉字
img = cv2.imread(referImg_list[0])
# 高斯去噪
image = cv2.GaussianBlur(img, (3, 3), 0)
# 灰度处理
gray_image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
# 自适应阈值处理
ret, image_ = cv2.threshold(gray_image, 0, 255, cv2.THRESH_OTSU)
#第一个汉字匹配
chepai_num.append(template_matching('chinese_words_list'))
print(chepai_num[0]) #匹配第二个英文字母
img = cv2.imread(referImg_list[1])
# 高斯去噪
image = cv2.GaussianBlur(img, (3, 3), 0)
# 灰度处理
gray_image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
# 自适应阈值处理
ret, image_ = cv2.threshold(gray_image, 0, 255, cv2.THRESH_OTSU)
#第二个英文字母匹配
chepai_num.append(template_matching('english_words_list'))
print(chepai_num[1]) #匹配其余5个字母,数字
for i in range(2,7):
img = cv2.imread(referImg_list[i])
# 高斯去噪
image = cv2.GaussianBlur(img, (3, 3), 0)
# 灰度处理
gray_image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
# 自适应阈值处理
ret, image_ = cv2.threshold(gray_image, 0, 255, cv2.THRESH_OTSU)
#其余字母匹配
chepai_num.append(template_matching('eng_num_words_list'))
print(chepai_num[i])
print(chepai_num)

基于opencv的车牌提取项目的更多相关文章

  1. 基于opencv的车牌识别系统

    前言 学习了很长一段时间了,需要沉淀下,而最好的办法就是做一个东西来应用学习的东西,同时也是一个学习的过程. 概述     OpenCV的全称是:Open Source Computer Vision ...

  2. 数字图像处理:基于MATLAB的车牌识别项目 标签: 图像处理matlab算法 2017-06-24 09:17 98人阅读 评论(0)

    学过了数字图像处理,就进行一个综合性强的小项目来巩固一下知识吧.前阵子编写调试了一套基于MATLAB的车牌识别的项目的代码.今天又重新改进了一下代码,识别的效果好一点了,也精简了一些代码.这里没有使用 ...

  3. OpenCV2学习笔记(十四):基于OpenCV卡通图片处理

    得知OpenCV有一段时间.除了研究的各种算法的内容.除了从备用,据导游书籍和资料,尝试结合链接的图像处理算法和日常生活,第一桌面上(随着摄像头)完成了一系列的视频流处理功能.开发平台Qt5.3.2+ ...

  4. Java基于opencv实现图像数字识别(二)—基本流程

    Java基于opencv实现图像数字识别(二)-基本流程 做一个项目之前呢,我们应该有一个总体把握,或者是进度条:来一步步的督促着我们来完成这个项目,在我们正式开始前呢,我们先讨论下流程. 我做的主要 ...

  5. 基于 OpenCV 的人脸识别

    基于 OpenCV 的人脸识别 一点背景知识 OpenCV 是一个开源的计算机视觉和机器学习库.它包含成千上万优化过的算法,为各种计算机视觉应用提供了一个通用工具包.根据这个项目的关于页面,OpenC ...

  6. 基于Opencv自带BP网络的车标简易识别

    代码地址如下:http://www.demodashi.com/demo/12966.html 记得把这几点描述好咯:代码实现过程 + 项目文件结构截图 + 演示效果 1.准备工作 1.1 训练集和测 ...

  7. 基于OpenCV的火焰检测(二)——RGB颜色判据

    上文跟大家分享了在做火焰检测中常用到的图像预处理方法,从这一篇博文开始,我将向大家介绍如何一步一步地检测出火焰区域.火焰提取要用 到很多判据,今天我要向大家介绍的是最简单的但是很有效的判据--RGB判 ...

  8. 【计算机视觉】基于OpenCV的人脸识别

    一点背景知识 OpenCV 是一个开源的计算机视觉和机器学习库.它包含成千上万优化过的算法,为各种计算机视觉应用提供了一个通用工具包.根据这个项目的关于页面,OpenCV 已被广泛运用在各种项目上,从 ...

  9. 基于Opencv识别,矫正二维码(C++)

    参考链接 [ 基于opencv 识别.定位二维码 (c++版) ](https://www.cnblogs.com/yuanchenhui/p/opencv_qr.html) OpenCV4.0.0二 ...

随机推荐

  1. Rocket - regmapper - RegField

    https://mp.weixin.qq.com/s/7WKB1QxcVzqm2Q7bWcKHzA 简单介绍RegField的实现. 1. 简单介绍 定义寄存器域相关的参数类型. 2. RegFiel ...

  2. Rocket - diplomacy - AddressDecoder

    https://mp.weixin.qq.com/s/UHGq74sEd9mcG5Q3f-g3mA   介绍AddressDecoder的实现.   ​​ 1. 基本定义   ​​ 每个Port包含多 ...

  3. 集合遍历元素的3种方法:for、foreach、迭代器iterator

    1.for循环方式(Set集合不能使用,因为Set是无序的没有索引) for (int i = 0; i < list.size(); i++) { Object o = list.get(i) ...

  4. ASP.NET生成验证码

    首先,添加一个一般处理程序 注释很详细了,有不懂的欢迎评论 using System; using System.Collections.Generic; using System.Drawing; ...

  5. Java实现 蓝桥杯 算法训练 多阶乘计算

    试题 算法训练 多阶乘计算 问题描述 我们知道,阶乘n!表示n*(n-1)(n-2)-21, 类似的,可以定义多阶乘计算,例如:5!!=531,依次可以有n!..!(k个'!',可以简单表示为n(k) ...

  6. Java实现 蓝桥杯 算法训练 关联矩阵

    算法训练 关联矩阵 时间限制:1.0s 内存限制:512.0MB 提交此题 问题描述 有一个n个结点m条边的有向图,请输出他的关联矩阵. 输入格式 第一行两个整数n.m,表示图中结点和边的数目.n&l ...

  7. java计算时间从什么时候开始 为什么从1970年开始 java的时间为什么是一大串数字

    Date date = new Date(0); System.out.println(date); 打印出来的结果: Thu Jan 01 08:00:00 CST 1970 也是1970 年 1 ...

  8. Java实现二分图的最大匹配

    1 问题描述 何为二分图的最大匹配问题? 引用自百度百科: 首先得说明一下何为匹配: 给定一个二分图G,在G的一个子图M中,M的边集{E}中的任意两条边都不依附于同一个顶点,则称M是一个匹配. 极大匹 ...

  9. 用户管理命令-passwd

    passwd可以给用户设置密码或者修改密码,超级用户可以修改任何用户的密码,而且可以不遵守密码的复杂性原则,普通用户只能修改自己的密码,必须遵守密码的复杂性原则 passwd [选项] 用户名 常用选 ...

  10. python—模块与包

    模块: (一个.py文件就是一个模块module,模块就是一组功能的集合体,我们的程序可以导入模块来复用模块里的功能.) 模块分三种: 1.python标准库 2.第三方模块 3.应用程序自定义模块 ...