執行環境:python 3.6、PyQt5 (pip install PyQt5)、百度SDK AipOcr (pip install baidu-aip)
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import sys
from aip import AipOcr
from PyQt5.QtWidgets import (QDialog, QApplication, QLabel, QPushButton,
QFileDialog, QMessageBox, QPlainTextEdit, QHBoxLayout,
QVBoxLayout)
from PyQt5.QtGui import QIcon, QFont
from PyQt5 import QtGui
import numbers
APP_ID = '17331753'
API_KEY = 'Sb3NN8WmLWNUtzkOfNHCavvu'
SECRET_KEY = 'x4tOqkoopegAgDyeyMoWWeCurLqVh3hX'
client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
options = {
'multi_detect': 'true',
}
class PlateRecognize(QDialog):
def __init__(self):
super(PlateRecognize, self).__init__()
self.text = ""
self.filePath = ""
self.numbers = []
self.initUI()
def initUI(self):
self.resize(500, 500)
self.setWindowTitle("車牌識別")
self.plabel = QLabel(self)
self.plabel.setFixedSize(400, 300)
self.obtn = QPushButton(self)
self.obtn.setText("打開本地圖片")
self.obtn.setFont(QFont("蘇新詩柳楷繁", 15))
self.obtn.clicked.connect(self.openimage)
self.obtn.setFixedSize(180, 40)
self.sbtn = QPushButton(self)
self.sbtn.setText("開 始 識 別")
self.sbtn.setFont(QFont("蘇新詩柳楷繁", 15))
self.sbtn.clicked.connect(self.recognize)
self.sbtn.setFixedSize(180, 40)
self.v1box = QVBoxLayout()
self.v1box.addWidget(self.obtn)
self.v1box.addWidget(self.sbtn)
self.h1box = QHBoxLayout()
self.h1box.addWidget(self.plabel)
self.h1box.addLayout(self.v1box)
self.tlabel = QLabel(self)
self.tlabel.setText("識\n別\n結\n果")
self.tlabel.setFont(QFont("蘇新詩柳楷繁", 15))
self.tlabel.resize(200, 50)
self.tedit = QPlainTextEdit(self)
self.tedit.setFont(QFont("宋體", 10))
self.tedit.setFixedSize(500, 100)
self.h2box = QHBoxLayout()
self.h2box.addStretch(1)
self.h2box.addWidget(self.tlabel)
self.h2box.addStretch(1)
self.h2box.addWidget(self.tedit)
self.h2box.addStretch(1)
self.vbox = QVBoxLayout()
self.vbox.addLayout(self.h1box)
self.vbox.addStretch(1)
self.vbox.addLayout(self.h2box)
self.setLayout(self.vbox)
def openimage(self):
self.filePath, imgType = QFileDialog.getOpenFileName(self, "打開本地圖片", "", "*.jpg;;*.png;;All Files(*)")
self.jpg = QtGui.QPixmap(self.filePath).scaled(self.plabel.width(), self.plabel.height())
self.plabel.setPixmap(self.jpg)
def recognize(self):
if(self.filePath == ""):
print(QMessageBox.warning(self, "警告", "請插入圖片", QMessageBox.Yes, QMessageBox.Yes))
return
result = client.licensePlate(self.get_file_content(self.filePath), options)
print(result)
plate = ''
for a in result['words_result']:
plate += a['number'] + '\n'
self.text = "車牌號碼:" + plate
print(QMessageBox.information(self, "提醒", "成功識別" + self.text, QMessageBox.Yes, QMessageBox.Yes))
self.tedit.setPlainText(self.text)
def get_file_content(self, filePath):
with open(filePath, 'rb') as fp:
return fp.read()
if __name__ == '__main__':
app = QApplication(sys.argv)
platerecognizeWindow = PlateRecognize()
platerecognizeWindow.show()
platerecognizeWindow.exec_()
sys.exit(app.exec_())
執行效果圖: