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