Repository: duanshengliu/End-to-end-for-chinese-plate-recognition Branch: master Commit: e47edd4aaf1f Files: 12 Total size: 19.5 MB Directory structure: gitextract__ge8bvgl/ ├── .gitignore ├── LICENSE ├── License-plate-recognition/ │ ├── CNN.py │ ├── UI.py │ ├── Unet.py │ ├── __init__.py │ ├── cnn.h5 │ ├── core.py │ ├── train.py │ └── unet.h5 ├── README.md └── requirements.txt ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ __pycache__/ ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS Copyright 2023 duanshengliu Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: License-plate-recognition/CNN.py ================================================ # -*- coding:utf-8 -*- # author: DuanshengLiu from tensorflow.keras import layers, losses, models import numpy as np import cv2 import os def cnn_train(): char_dict = {"京": 0, "沪": 1, "津": 2, "渝": 3, "冀": 4, "晋": 5, "蒙": 6, "辽": 7, "吉": 8, "黑": 9, "苏": 10, "浙": 11, "皖": 12, "闽": 13, "赣": 14, "鲁": 15, "豫": 16, "鄂": 17, "湘": 18, "粤": 19, "桂": 20, "琼": 21, "川": 22, "贵": 23, "云": 24, "藏": 25, "陕": 26, "甘": 27, "青": 28, "宁": 29, "新": 30, "0": 31, "1": 32, "2": 33, "3": 34, "4": 35, "5": 36, "6": 37, "7": 38, "8": 39, "9": 40, "A": 41, "B": 42, "C": 43, "D": 44, "E": 45, "F": 46, "G": 47, "H": 48, "J": 49, "K": 50, "L": 51, "M": 52, "N": 53, "P": 54, "Q": 55, "R": 56, "S": 57, "T": 58, "U": 59, "V": 60, "W": 61, "X": 62, "Y": 63, "Z": 64} # 读取数据集 path = 'home/cnn_datasets/' # 车牌号数据集路径(车牌图片宽240,高80) pic_name = sorted(os.listdir(path)) n = len(pic_name) X_train, y_train = [], [] for i in range(n): print("正在读取第%d张图片" % i) img = cv2.imdecode(np.fromfile(path + pic_name[i], dtype=np.uint8), -1) # cv2.imshow无法读取中文路径图片,改用此方式 label = [char_dict[name] for name in pic_name[i][0:7]] # 图片名前7位为车牌标签 X_train.append(img) y_train.append(label) X_train = np.array(X_train) y_train = [np.array(y_train)[:, i] for i in range(7)] # y_train是长度为7的列表,其中每个都是shape为(n,)的ndarray,分别对应n张图片的第一个字符,第二个字符....第七个字符 # cnn模型 Input = layers.Input((80, 240, 3)) # 车牌图片shape(80,240,3) x = Input x = layers.Conv2D(filters=16, kernel_size=(3, 3), strides=1, padding='same', activation='relu')(x) x = layers.MaxPool2D(pool_size=(2, 2), padding='same', strides=2)(x) for i in range(3): x = layers.Conv2D(filters=32 * 2 ** i, kernel_size=(3, 3), padding='valid', activation='relu')(x) x = layers.Conv2D(filters=32 * 2 ** i, kernel_size=(3, 3), padding='valid', activation='relu')(x) x = layers.MaxPool2D(pool_size=(2, 2), padding='same', strides=2)(x) x = layers.Dropout(0.5)(x) x = layers.Flatten()(x) x = layers.Dropout(0.3)(x) Output = [layers.Dense(65, activation='softmax', name='c%d' % (i + 1))(x) for i in range(7)] # 7个输出分别对应车牌7个字符,每个输出都为65个类别类概率 model = models.Model(inputs=Input, outputs=Output) model.summary() model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', # y_train未进行one-hot编码,所以loss选择sparse_categorical_crossentropy metrics=['accuracy']) # 模型训练 print("开始训练cnn") model.fit(X_train, y_train, epochs=35) # 总loss为7个loss的和 model.save('cnn.h5') print('cnn.h5保存成功!!!') def cnn_predict(cnn, Lic_img): characters = ["京", "沪", "津", "渝", "冀", "晋", "蒙", "辽", "吉", "黑", "苏", "浙", "皖", "闽", "赣", "鲁", "豫", "鄂", "湘", "粤", "桂", "琼", "川", "贵", "云", "藏", "陕", "甘", "青", "宁", "新", "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"] Lic_pred = [] for lic in Lic_img: lic_pred = cnn.predict(lic.reshape(1, 80, 240, 3)) # 预测形状应为(1,80,240,3) lic_pred = np.array(lic_pred).reshape(7, 65) # 列表转为ndarray,形状为(7,65) if len(lic_pred[lic_pred >= 0.8]) >= 4: # 统计其中预测概率值大于80%以上的个数,大于等于4个以上认为识别率高,识别成功 chars = '' for arg in np.argmax(lic_pred, axis=1): # 取每行中概率值最大的arg,将其转为字符 chars += characters[arg] chars = chars[0:2] + '·' + chars[2:] Lic_pred.append((lic, chars)) # 将车牌和识别结果一并存入Lic_pred return Lic_pred ================================================ FILE: License-plate-recognition/UI.py ================================================ # -*- coding:utf-8 -*- # author: DuanshengLiu import cv2 import sys import numpy as np from tkinter import * from tkinter.filedialog import askopenfilename from PIL import Image, ImageTk from tensorflow import keras from core import locate_and_correct from Unet import unet_predict from CNN import cnn_predict class Window: def __init__(self, win, ww, wh): self.win = win self.ww = ww self.wh = wh self.win.geometry("%dx%d+%d+%d" % (ww, wh, 200, 50)) # 界面启动时的初始位置 self.win.title("车牌定位,矫正和识别软件---by DuanshengLiu") self.img_src_path = None self.label_src = Label(self.win, text='原图:', font=('微软雅黑', 13)).place(x=0, y=0) self.label_lic1 = Label(self.win, text='车牌区域1:', font=('微软雅黑', 13)).place(x=615, y=0) self.label_pred1 = Label(self.win, text='识别结果1:', font=('微软雅黑', 13)).place(x=615, y=85) self.label_lic2 = Label(self.win, text='车牌区域2:', font=('微软雅黑', 13)).place(x=615, y=180) self.label_pred2 = Label(self.win, text='识别结果2:', font=('微软雅黑', 13)).place(x=615, y=265) self.label_lic3 = Label(self.win, text='车牌区域3:', font=('微软雅黑', 13)).place(x=615, y=360) self.label_pred3 = Label(self.win, text='识别结果3:', font=('微软雅黑', 13)).place(x=615, y=445) self.can_src = Canvas(self.win, width=512, height=512, bg='white', relief='solid', borderwidth=1) # 原图画布 self.can_src.place(x=50, y=0) self.can_lic1 = Canvas(self.win, width=245, height=85, bg='white', relief='solid', borderwidth=1) # 车牌区域1画布 self.can_lic1.place(x=710, y=0) self.can_pred1 = Canvas(self.win, width=245, height=65, bg='white', relief='solid', borderwidth=1) # 车牌识别1画布 self.can_pred1.place(x=710, y=90) self.can_lic2 = Canvas(self.win, width=245, height=85, bg='white', relief='solid', borderwidth=1) # 车牌区域2画布 self.can_lic2.place(x=710, y=175) self.can_pred2 = Canvas(self.win, width=245, height=65, bg='white', relief='solid', borderwidth=1) # 车牌识别2画布 self.can_pred2.place(x=710, y=265) self.can_lic3 = Canvas(self.win, width=245, height=85, bg='white', relief='solid', borderwidth=1) # 车牌区域3画布 self.can_lic3.place(x=710, y=350) self.can_pred3 = Canvas(self.win, width=245, height=65, bg='white', relief='solid', borderwidth=1) # 车牌识别3画布 self.can_pred3.place(x=710, y=440) self.button1 = Button(self.win, text='选择文件', width=10, height=1, command=self.load_show_img) # 选择文件按钮 self.button1.place(x=680, y=wh - 30) self.button2 = Button(self.win, text='识别车牌', width=10, height=1, command=self.display) # 识别车牌按钮 self.button2.place(x=780, y=wh - 30) self.button3 = Button(self.win, text='清空所有', width=10, height=1, command=self.clear) # 清空所有按钮 self.button3.place(x=880, y=wh - 30) self.unet = keras.models.load_model('unet.h5') self.cnn = keras.models.load_model('cnn.h5') print('正在启动中,请稍等...') cnn_predict(self.cnn, [np.zeros((80, 240, 3))]) print("已启动,开始识别吧!") def load_show_img(self): self.clear() sv = StringVar() sv.set(askopenfilename()) self.img_src_path = Entry(self.win, state='readonly', text=sv).get() # 获取到所打开的图片 img_open = Image.open(self.img_src_path) if img_open.size[0] * img_open.size[1] > 240 * 80: img_open = img_open.resize((512, 512), Image.ANTIALIAS) self.img_Tk = ImageTk.PhotoImage(img_open) self.can_src.create_image(258, 258, image=self.img_Tk, anchor='center') def display(self): if self.img_src_path == None: # 还没选择图片就进行预测 self.can_pred1.create_text(32, 15, text='请选择图片', anchor='nw', font=('黑体', 28)) else: img_src = cv2.imdecode(np.fromfile(self.img_src_path, dtype=np.uint8), -1) # 从中文路径读取时用 h, w = img_src.shape[0], img_src.shape[1] if h * w <= 240 * 80 and 2 <= w / h <= 5: # 满足该条件说明可能整个图片就是一张车牌,无需定位,直接识别即可 lic = cv2.resize(img_src, dsize=(240, 80), interpolation=cv2.INTER_AREA)[:, :, :3] # 直接resize为(240,80) img_src_copy, Lic_img = img_src, [lic] else: # 否则就需通过unet对img_src原图预测,得到img_mask,实现车牌定位,然后进行识别 img_src, img_mask = unet_predict(self.unet, self.img_src_path) img_src_copy, Lic_img = locate_and_correct(img_src, img_mask) # 利用core.py中的locate_and_correct函数进行车牌定位和矫正 Lic_pred = cnn_predict(self.cnn, Lic_img) # 利用cnn进行车牌的识别预测,Lic_pred中存的是元祖(车牌图片,识别结果) if Lic_pred: img = Image.fromarray(img_src_copy[:, :, ::-1]) # img_src_copy[:, :, ::-1]将BGR转为RGB self.img_Tk = ImageTk.PhotoImage(img) self.can_src.delete('all') # 显示前,先清空画板 self.can_src.create_image(258, 258, image=self.img_Tk, anchor='center') # img_src_copy上绘制出了定位的车牌轮廓,将其显示在画板上 for i, lic_pred in enumerate(Lic_pred): if i == 0: self.lic_Tk1 = ImageTk.PhotoImage(Image.fromarray(lic_pred[0][:, :, ::-1])) self.can_lic1.create_image(5, 5, image=self.lic_Tk1, anchor='nw') self.can_pred1.create_text(35, 15, text=lic_pred[1], anchor='nw', font=('黑体', 28)) elif i == 1: self.lic_Tk2 = ImageTk.PhotoImage(Image.fromarray(lic_pred[0][:, :, ::-1])) self.can_lic2.create_image(5, 5, image=self.lic_Tk2, anchor='nw') self.can_pred2.create_text(40, 15, text=lic_pred[1], anchor='nw', font=('黑体', 28)) elif i == 2: self.lic_Tk3 = ImageTk.PhotoImage(Image.fromarray(lic_pred[0][:, :, ::-1])) self.can_lic3.create_image(5, 5, image=self.lic_Tk3, anchor='nw') self.can_pred3.create_text(40, 15, text=lic_pred[1], anchor='nw', font=('黑体', 28)) else: # Lic_pred为空说明未能识别 self.can_pred1.create_text(47, 15, text='未能识别', anchor='nw', font=('黑体', 27)) def clear(self): self.can_src.delete('all') self.can_lic1.delete('all') self.can_lic2.delete('all') self.can_lic3.delete('all') self.can_pred1.delete('all') self.can_pred2.delete('all') self.can_pred3.delete('all') self.img_src_path = None def closeEvent(): # 关闭前清除session(),防止'NoneType' object is not callable keras.backend.clear_session() sys.exit() if __name__ == '__main__': win = Tk() ww = 1000 # 窗口宽设定1000 wh = 600 # 窗口高设定600 Window(win, ww, wh) win.protocol("WM_DELETE_WINDOW", Window.closeEvent) win.mainloop() ================================================ FILE: License-plate-recognition/Unet.py ================================================ # -*- coding:utf-8 -*- # author: DuanshengLiu import numpy as np import os import cv2 from tensorflow.keras import layers, losses, models def unet_train(): height = 512 width = 512 path = 'D:/desktop/unet_datasets/' input_name = os.listdir(path + 'train_image') n = len(input_name) print(n) X_train, y_train = [], [] for i in range(n): print("正在读取第%d张图片" % i) img = cv2.imread(path + 'train_image/%d.png' % i) label = cv2.imread(path + 'train_label/%d.png' % i) X_train.append(img) y_train.append(label) X_train = np.array(X_train) y_train = np.array(y_train) def Conv2d_BN(x, nb_filter, kernel_size, strides=(1, 1), padding='same'): x = layers.Conv2D(nb_filter, kernel_size, strides=strides, padding=padding)(x) x = layers.BatchNormalization(axis=3)(x) x = layers.LeakyReLU(alpha=0.1)(x) return x def Conv2dT_BN(x, filters, kernel_size, strides=(2, 2), padding='same'): x = layers.Conv2DTranspose(filters, kernel_size, strides=strides, padding=padding)(x) x = layers.BatchNormalization(axis=3)(x) x = layers.LeakyReLU(alpha=0.1)(x) return x inpt = layers.Input(shape=(height, width, 3)) conv1 = Conv2d_BN(inpt, 8, (3, 3)) conv1 = Conv2d_BN(conv1, 8, (3, 3)) pool1 = layers.MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='same')(conv1) conv2 = Conv2d_BN(pool1, 16, (3, 3)) conv2 = Conv2d_BN(conv2, 16, (3, 3)) pool2 = layers.MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='same')(conv2) conv3 = Conv2d_BN(pool2, 32, (3, 3)) conv3 = Conv2d_BN(conv3, 32, (3, 3)) pool3 = layers.MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='same')(conv3) conv4 = Conv2d_BN(pool3, 64, (3, 3)) conv4 = Conv2d_BN(conv4, 64, (3, 3)) pool4 = layers.MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='same')(conv4) conv5 = Conv2d_BN(pool4, 128, (3, 3)) conv5 = layers.Dropout(0.5)(conv5) conv5 = Conv2d_BN(conv5, 128, (3, 3)) conv5 = layers.Dropout(0.5)(conv5) convt1 = Conv2dT_BN(conv5, 64, (3, 3)) concat1 = layers.concatenate([conv4, convt1], axis=3) concat1 = layers.Dropout(0.5)(concat1) conv6 = Conv2d_BN(concat1, 64, (3, 3)) conv6 = Conv2d_BN(conv6, 64, (3, 3)) convt2 = Conv2dT_BN(conv6, 32, (3, 3)) concat2 = layers.concatenate([conv3, convt2], axis=3) concat2 = layers.Dropout(0.5)(concat2) conv7 = Conv2d_BN(concat2, 32, (3, 3)) conv7 = Conv2d_BN(conv7, 32, (3, 3)) convt3 = Conv2dT_BN(conv7, 16, (3, 3)) concat3 = layers.concatenate([conv2, convt3], axis=3) concat3 = layers.Dropout(0.5)(concat3) conv8 = Conv2d_BN(concat3, 16, (3, 3)) conv8 = Conv2d_BN(conv8, 16, (3, 3)) convt4 = Conv2dT_BN(conv8, 8, (3, 3)) concat4 = layers.concatenate([conv1, convt4], axis=3) concat4 = layers.Dropout(0.5)(concat4) conv9 = Conv2d_BN(concat4, 8, (3, 3)) conv9 = Conv2d_BN(conv9, 8, (3, 3)) conv9 = layers.Dropout(0.5)(conv9) outpt = layers.Conv2D(filters=3, kernel_size=(1, 1), strides=(1, 1), padding='same', activation='relu')(conv9) # TODO:activation='softmax' model = models.Model(inpt, outpt) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.summary() print("开始训练u-net") model.fit(X_train, y_train, epochs=100, batch_size=15)#epochs和batch_size看个人情况调整,batch_size不要过大,否则内存容易溢出 #我11G显存也只能设置15-20左右,我训练最终loss降低至250左右,acc约95%左右 model.save('unet.h5') print('unet.h5保存成功!!!') def unet_predict(unet, img_src_path): img_src = cv2.imdecode(np.fromfile(img_src_path, dtype=np.uint8), -1) # 从中文路径读取时用 # img_src=cv2.imread(img_src_path) if img_src.shape != (512, 512, 3): img_src = cv2.resize(img_src, dsize=(512, 512), interpolation=cv2.INTER_AREA)[:, :, :3] # dsize=(宽度,高度),[:,:,:3]是防止图片为4通道图片,后续无法reshape img_src = img_src.reshape(1, 512, 512, 3) # 预测图片shape为(1,512,512,3) img_mask = unet.predict(img_src) # 归一化除以255后进行预测 img_src = img_src.reshape(512, 512, 3) # 将原图reshape为3维 img_mask = img_mask.reshape(512, 512, 3) # 将预测后图片reshape为3维 img_mask = img_mask / np.max(img_mask) * 255 # 归一化后乘以255 img_mask[:, :, 2] = img_mask[:, :, 1] = img_mask[:, :, 0] # 三个通道保持相同 img_mask = img_mask.astype(np.uint8) # 将img_mask类型转为int型 return img_src, img_mask ================================================ FILE: License-plate-recognition/__init__.py ================================================ ================================================ FILE: License-plate-recognition/cnn.h5 ================================================ [File too large to display: 19.5 MB] ================================================ FILE: License-plate-recognition/core.py ================================================ # -*- coding:utf-8 -*- # author: DuanshengLiu import cv2 import numpy as np def locate_and_correct(img_src, img_mask): """ 该函数通过cv2对img_mask进行边缘检测,获取车牌区域的边缘坐标(存储在contours中)和最小外接矩形4个端点坐标, 再从车牌的边缘坐标中计算出和最小外接矩形4个端点最近的点即为平行四边形车牌的四个端点,从而实现车牌的定位和矫正 :param img_src: 原始图片 :param img_mask: 通过u_net进行图像分隔得到的二值化图片,车牌区域呈现白色,背景区域为黑色 :return: 定位且矫正后的车牌 """ # cv2.imshow('img_mask',img_mask) # cv2.waitKey(0) # ret,thresh = cv2.threshold(img_mask[:,:,0],0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) #二值化 # cv2.imshow('thresh',thresh) # cv2.waitKey(0) try: contours, hierarchy = cv2.findContours(img_mask[:, :, 0], cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) except: # 防止opencv版本不一致报错 ret, contours, hierarchy = cv2.findContours(img_mask[:, :, 0], cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) if not len(contours): # contours1长度为0说明未检测到车牌 # print("未检测到车牌") return [], [] else: Lic_img = [] img_src_copy = img_src.copy() # img_src_copy用于绘制出定位的车牌轮廓 for ii, cont in enumerate(contours): x, y, w, h = cv2.boundingRect(cont) # 获取最小外接矩形 img_cut_mask = img_mask[y:y + h, x:x + w] # 将标签车牌区域截取出来 # cv2.imshow('img_cut_mask',img_cut_mask) # cv2.waitKey(0) # print('w,h,均值,宽高比',w,h,np.mean(img_cut_mask),w/h) # contours中除了车牌区域可能会有宽或高都是1或者2这样的小噪点, # 而待选车牌区域的均值应较高,且宽和高不会非常小,因此通过以下条件进行筛选 if np.mean(img_cut_mask) >= 75 and w > 15 and h > 15: rect = cv2.minAreaRect(cont) # 针对坐标点获取带方向角的最小外接矩形,中心点坐标,宽高,旋转角度 box = cv2.boxPoints(rect).astype(np.int32) # 获取最小外接矩形四个顶点坐标 # cv2.drawContours(img_mask, contours, -1, (0, 0, 255), 2) # cv2.drawContours(img_mask, [box], 0, (0, 255, 0), 2) # cv2.imshow('img_mask',img_mask) # cv2.waitKey(0) cont = cont.reshape(-1, 2).tolist() # 由于转换矩阵的两组坐标位置需要一一对应,因此需要将最小外接矩形的坐标进行排序,最终排序为[左上,左下,右上,右下] box = sorted(box, key=lambda xy: xy[0]) # 先按照左右进行排序,分为左侧的坐标和右侧的坐标 box_left, box_right = box[:2], box[2:] # 此时box的前2个是左侧的坐标,后2个是右侧的坐标 box_left = sorted(box_left, key=lambda x: x[1]) # 再按照上下即y进行排序,此时box_left中为左上和左下两个端点坐标 box_right = sorted(box_right, key=lambda x: x[1]) # 此时box_right中为右上和右下两个端点坐标 box = np.array(box_left + box_right) # [左上,左下,右上,右下] # print(box) x0, y0 = box[0][0], box[0][1] # 这里的4个坐标即为最小外接矩形的四个坐标,接下来需获取平行(或不规则)四边形的坐标 x1, y1 = box[1][0], box[1][1] x2, y2 = box[2][0], box[2][1] x3, y3 = box[3][0], box[3][1] def point_to_line_distance(X, Y): if x2 - x0: k_up = (y2 - y0) / (x2 - x0) # 斜率不为无穷大 d_up = abs(k_up * X - Y + y2 - k_up * x2) / (k_up ** 2 + 1) ** 0.5 else: # 斜率无穷大 d_up = abs(X - x2) if x1 - x3: k_down = (y1 - y3) / (x1 - x3) # 斜率不为无穷大 d_down = abs(k_down * X - Y + y1 - k_down * x1) / (k_down ** 2 + 1) ** 0.5 else: # 斜率无穷大 d_down = abs(X - x1) return d_up, d_down d0, d1, d2, d3 = np.inf, np.inf, np.inf, np.inf l0, l1, l2, l3 = (x0, y0), (x1, y1), (x2, y2), (x3, y3) for each in cont: # 计算cont中的坐标与矩形四个坐标的距离以及到上下两条直线的距离,对距离和进行权重的添加,成功计算选出四边形的4个顶点坐标 x, y = each[0], each[1] dis0 = (x - x0) ** 2 + (y - y0) ** 2 dis1 = (x - x1) ** 2 + (y - y1) ** 2 dis2 = (x - x2) ** 2 + (y - y2) ** 2 dis3 = (x - x3) ** 2 + (y - y3) ** 2 d_up, d_down = point_to_line_distance(x, y) weight = 0.975 if weight * d_up + (1 - weight) * dis0 < d0: # 小于则更新 d0 = weight * d_up + (1 - weight) * dis0 l0 = (x, y) if weight * d_down + (1 - weight) * dis1 < d1: d1 = weight * d_down + (1 - weight) * dis1 l1 = (x, y) if weight * d_up + (1 - weight) * dis2 < d2: d2 = weight * d_up + (1 - weight) * dis2 l2 = (x, y) if weight * d_down + (1 - weight) * dis3 < d3: d3 = weight * d_down + (1 - weight) * dis3 l3 = (x, y) # print([l0,l1,l2,l3]) # for l in [l0, l1, l2, l3]: # cv2.circle(img=img_mask, color=(0, 255, 255), center=tuple(l), thickness=2, radius=2) # cv2.imshow('img_mask',img_mask) # cv2.waitKey(0) p0 = np.float32([l0, l1, l2, l3]) # 左上角,左下角,右上角,右下角,p0和p1中的坐标顺序对应,以进行转换矩阵的形成 p1 = np.float32([(0, 0), (0, 80), (240, 0), (240, 80)]) # 我们所需的长方形 transform_mat = cv2.getPerspectiveTransform(p0, p1) # 构成转换矩阵 lic = cv2.warpPerspective(img_src, transform_mat, (240, 80)) # 进行车牌矫正 # cv2.imshow('lic',lic) # cv2.waitKey(0) Lic_img.append(lic) cv2.drawContours(img_src_copy, [np.array([l0, l1, l3, l2])], -1, (0, 255, 0), 2) # 在img_src_copy上绘制出定位的车牌轮廓,(0, 255, 0)表示绘制线条为绿色 return img_src_copy, Lic_img ================================================ FILE: License-plate-recognition/train.py ================================================ # -*- coding:utf-8 -*- # author: DuanshengLiu from Unet import unet_train from CNN import cnn_train unet_train()#训练后得到unet.h5,用于车牌定位 cnn_train()#训练后得到cnn.h5,用于车牌识别 ================================================ FILE: README.md ================================================ # End-to-end-for-chinese-plate-recognition ## 基于u-net,cv2以及cnn的中文车牌定位,矫正和端到端识别软件,其中unet和cv2用于车牌定位和矫正,cnn进行车牌识别,unet和cnn都是基于tensorflow的keras实现 ## 环境:python:3.6, tensorflow:1.15.2, opencv: 4.1.0.25, keras: 2.3.1 ### 整体思路:1. 利用u-net图像分割得到二值化图像,2. 再使用cv2进行边缘检测获得车牌区域坐标,并将车牌图形矫正,3. 利用卷积神经网络cnn进行车牌多标签端到端识别,具体描述可见CSDN博客:https://blog.csdn.net/qq_32194791/article/details/106748685 ### 实现效果:拍摄角度倾斜、强曝光或昏暗环境等都能较好地识别,甚至有些百度AI车牌识别未能识别的图片也能识别 ### 注意:若是直接识别类似下图的无需定位的完整车牌,那么请确保图片尺寸小于等于240 * 80,否则会被认为图片中含其余区域而进行定位,反而识别效果不佳 ![](https://github.com/duanshengliu/End-to-end-for-chinese-plate-recognition/blob/master/test_pic/lic.png) ### 其余的没什么问题,正常识别都可以 ### 部分效果图: ![](https://github.com/duanshengliu/End-to-end-for-chinese-plate-recognition/blob/master/test_pic/0.png) ![](https://github.com/duanshengliu/End-to-end-for-chinese-plate-recognition/blob/master/test_pic/1.png) ![](https://github.com/duanshengliu/End-to-end-for-chinese-plate-recognition/blob/master/test_pic/2.png) ![](https://github.com/duanshengliu/End-to-end-for-chinese-plate-recognition/blob/master/test_pic/3.png) ![](https://github.com/duanshengliu/End-to-end-for-chinese-plate-recognition/blob/master/test_pic/4.png) ![](https://github.com/duanshengliu/End-to-end-for-chinese-plate-recognition/blob/master/test_pic/5.png) ![](https://github.com/duanshengliu/End-to-end-for-chinese-plate-recognition/blob/master/test_pic/6.png) ![](https://github.com/duanshengliu/End-to-end-for-chinese-plate-recognition/blob/master/test_pic/7.png) ================================================ FILE: requirements.txt ================================================ tensorflow==1.15.2 opencv-python==4.1.0.25 keras==2.3.1 pillow==9.0.0