深度学习实例2_车牌识别分割——自学笔记

python 复制代码
import cv2
from matplotlib import pyplot as plt
import os
import numpy as np
from PIL import ImageFont, ImageDraw, Image

彩色图片显示

python 复制代码
def plt_show0(img):
    b,g,r = cv2.split(img)
    img = cv2.merge([r, g, b])
    plt.imshow(img)
    plt.show()

灰度图片显示

python 复制代码
def plt_show(img):
    plt.imshow(img,cmap='gray')
    plt.show()

图像去噪

python 复制代码
def gray_guss(image):
    image = cv2.GaussianBlur(image, (3, 3), 0)
    gray_image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
    return gray_image

图像预处理

读取图像

python 复制代码
origin_image = cv2.imread("car3.png")

高斯去噪

python 复制代码
# 复制一张图片,在复制图上进行图像操作,保留原图
image = origin_image.copy()
gray_image = gray_guss(image)

边缘检测

python 复制代码
Sobel_x = cv2.Sobel(gray_image, cv2.CV_16S, 1, 0)
absX = cv2.convertScaleAbs(Sobel_x)
image = absX

阈值化

python 复制代码
# 图像阈值化操作------获得二值化图
ret, image = cv2.threshold(image, 0, 255, cv2.THRESH_OTSU)
# 显示灰度图像
plt_show(image)

车牌定位

区域的选择

python 复制代码
kernelX = cv2.getStructuringElement(cv2.MORPH_RECT, (30, 10))
image = cv2.morphologyEx(image, cv2.MORPH_CLOSE, kernelX,iterations = 1)
# 显示灰度图像
plt_show(image)

形态学操作

python 复制代码
# 腐蚀(erode)和膨胀(dilate)
kernelX = cv2.getStructuringElement(cv2.MORPH_RECT, (50, 1))
kernelY = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 20))
#x方向进行闭操作(抑制暗细节)
image = cv2.dilate(image, kernelX)
image = cv2.erode(image, kernelX)
#y方向的开操作
image = cv2.erode(image, kernelY)
image = cv2.dilate(image, kernelY)
# 中值滤波(去噪)
image = cv2.medianBlur(image, 21)
# 显示灰度图像
plt_show(image)

轮廓检验

python 复制代码
contours, hierarchy = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for item in contours:
    rect = cv2.boundingRect(item)
    x = rect[0]
    y = rect[1]
    weight = rect[2]
    height = rect[3]
    # 根据轮廓的形状特点,确定车牌的轮廓位置并截取图像
    if (weight > (height * 3)) and (weight < (height * 4.5)):
        image = origin_image[y:y + height, x:x + weight]
        plt_show(image)

车牌字符分割

高斯去噪

python 复制代码
# 图像去噪灰度处理
gray_image = gray_guss(image)

阈值化

python 复制代码
ret, image = cv2.threshold(gray_image, 0, 255, cv2.THRESH_OTSU)
plt_show(image)

膨胀操作

python 复制代码
#膨胀操作
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (4, 4))
image = cv2.dilate(image, kernel)
plt_show(image)

车牌号顺序

python 复制代码
words = sorted(words,key=lambda s:s[0],reverse=False)
i = 0
#word中存放轮廓的起始点和宽高
for word in words:
    # 筛选字符的轮廓
    if (word[3] > (word[2] * 1.5)) and (word[3] < (word[2] * 5.5)) and (word[2] > 10):
        i = i+1
        if word[2] < 15:
            splite_image = image[word[1]:word[1] + word[3], word[0]-word[2]:word[0] + word[2]*2]
        else:
            splite_image = image[word[1]:word[1] + word[3], word[0]:word[0] + word[2]]
        word_images.append(splite_image)
        print(i)
print(words)
1
2
3
4
5
6
7
[[0, 27, 3, 13], [3, 0, 85, 101], [16, 52, 10, 30], [16, 33, 10, 11], [20, 13, 9, 12], [26, 42, 21, 43], [27, 12, 29, 29], [45, 41, 9, 44], [62, 12, 43, 74], [91, 0, 9, 4], [102, 99, 15, 2], [112, 45, 11, 10], [129, 14, 43, 73], [178, 15, 42, 73], [225, 14, 40, 73], [233, 98, 39, 3], [272, 88, 10, 7], [274, 13, 40, 73], [279, 0, 10, 6], [285, 0, 89, 101], [331, 13, 15, 72]]

分割效果

python 复制代码
for i,j in enumerate(word_images):
    plt.subplot(1,7,i+1)
    plt.imshow(word_images[i],cmap='gray')
plt.show()
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-40-97859dfa300a> in <cell line: 1>()
      1 for i,j in enumerate(word_images):
----> 2     plt.subplot(1,7,i+1)
      3     plt.imshow(word_images[i],cmap='gray')
      4 plt.show()


/usr/local/lib/python3.10/dist-packages/matplotlib/pyplot.py in subplot(*args, **kwargs)
   1321 
   1322     # First, search for an existing subplot with a matching spec.
-> 1323     key = SubplotSpec._from_subplot_args(fig, args)
   1324 
   1325     for ax in fig.axes:


/usr/local/lib/python3.10/dist-packages/matplotlib/gridspec.py in _from_subplot_args(figure, args)
    596         else:
    597             if not isinstance(num, Integral) or num < 1 or num > rows*cols:
--> 598                 raise ValueError(
    599                     f"num must be an integer with 1 <= num <= {rows*cols}, "
    600                     f"not {num!r}"


ValueError: num must be an integer with 1 <= num <= 7, not 8

模板准备

colab中解压文件

python 复制代码
import zipfile
import os

# 假设你上传的ZIP文件名为'example.zip',并且它位于Colab的当前工作目录中
zip_file_path = 'License Plate Recognition.zip'

# 设置解压的目标目录(例如,解压到当前工作目录下的'extracted_folder')
extract_dir = 'extracted_folder'

# 如果目标目录已经存在,则删除它(可选)
if os.path.exists(extract_dir):
    import shutil
    shutil.rmtree(extract_dir)

# 使用zipfile模块解压ZIP文件
with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
    zip_ref.extractall(extract_dir)

# 现在,'extracted_folder'目录中应该包含了ZIP文件中的所有文件和文件夹
# 验证解压
print(os.listdir(extract_dir))
['License Plate Recognition']
python 复制代码
# 准备模板(template[0-9]为数字模板;)
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',
            '藏','川','鄂','甘','赣','贵','桂','黑','沪','吉','冀','津','晋','京','辽','鲁','蒙','闽','宁',
            '青','琼','陕','苏','皖','湘','新','渝','豫','粤','云','浙']

# 读取一个文件夹下的所有图片,输入参数是文件名,返回模板文件地址列表
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('D:/refer1/'+ template[i])
        chinese_words_list.append(c_word)
    return chinese_words_list
chinese_words_list = get_chinese_words_list()


# 获得英文模板列表(只匹配车牌的第二个字符)
def get_eng_words_list():
    eng_words_list = []
    for i in range(10,34):
        e_word = read_directory('D:/refer1/'+ template[i])
        eng_words_list.append(e_word)
    return eng_words_list
eng_words_list = get_eng_words_list()


# 获得英文和数字模板列表(匹配车牌后面的字符)
def get_eng_num_words_list():
    eng_num_words_list = []
    for i in range(0,34):
        word = read_directory('D:/refer1/'+ template[i])
        eng_num_words_list.append(word)
    return eng_num_words_list
eng_num_words_list = get_eng_num_words_list()
---------------------------------------------------------------------------

FileNotFoundError                         Traceback (most recent call last)

<ipython-input-4-6b0c5e30ad5b> in <cell line: 22>()
     20         chinese_words_list.append(c_word)
     21     return chinese_words_list
---> 22 chinese_words_list = get_chinese_words_list()
     23 
     24 


<ipython-input-4-6b0c5e30ad5b> in get_chinese_words_list()
     17     for i in range(34,64):
     18         #将模板存放在字典中
---> 19         c_word = read_directory('D:/refer1/'+ template[i])
     20         chinese_words_list.append(c_word)
     21     return chinese_words_list


<ipython-input-4-6b0c5e30ad5b> in read_directory(directory_name)
      8 def read_directory(directory_name):
      9     referImg_list = []
---> 10     for filename in os.listdir(directory_name):
     11         referImg_list.append(directory_name + "/" + filename)
     12     return referImg_list


FileNotFoundError: [Errno 2] No such file or directory: 'D:/refer1/藏'
python 复制代码
相关推荐
可喜~可乐8 分钟前
循环神经网络(RNN)入门指南:从原理到实践
人工智能·rnn·深度学习·神经网络·机器学习·lstm
Adenialzz39 分钟前
Rectified Flow 原理简介与示例代码解读
人工智能·深度学习·机器学习·计算机视觉·diffusion
winner88811 小时前
强化学习基础之贝尔曼期望方程
深度学习·贝尔曼方程·马尔科夫链
少说多想勤做2 小时前
【前沿 热点 顶会】AAAI 2025中与目标检测有关的论文
人工智能·深度学习·神经网络·目标检测·计算机视觉·目标跟踪·aaai
橙子小哥的代码世界4 小时前
【计算机视觉基础CV-图像分类】05 - 深入解析ResNet与GoogLeNet:从基础理论到实际应用
图像处理·人工智能·深度学习·神经网络·计算机视觉·分类·卷积神经网络
leigm1234 小时前
深度学习使用Anaconda打开Jupyter Notebook编码
人工智能·深度学习·jupyter
阿正的梦工坊7 小时前
深入理解 PyTorch 的 view() 函数:以多头注意力机制(Multi-Head Attention)为例 (中英双语)
人工智能·pytorch·python
人类群星闪耀时10 小时前
深度学习在灾难恢复中的作用:智能运维的新时代
运维·人工智能·深度学习
机器懒得学习10 小时前
从随机生成到深度学习:使用DCGAN和CycleGAN生成图像的实战教程
人工智能·深度学习
烟波人长安吖~11 小时前
【目标跟踪+人流计数+人流热图(Web界面)】基于YOLOV11+Vue+SpringBoot+Flask+MySQL
vue.js·pytorch·spring boot·深度学习·yolo·目标跟踪