初学图像处理,做了一个车牌提取项目,本博客仅仅是为了记录一下学习过程,该项目只具备初级功能,还有待改善
第一部分:车牌倾斜矫正
# 导入所需模块
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_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)
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)
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)
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)
手机扫一扫
移动阅读更方便
你可能感兴趣的文章