当前位置:   article > 正文

用Python编写百度ocr图像识别程序_利用百度ocr python

利用百度ocr python

涉及的知识点:Python、调用百度API、PyQt5

运行环境:Mac+Python3.7+PyQt5

程序截图:


实现步骤:

第一步:获得自己的百度OCR的AK和SK

1、利用百度 AI 开发平台的 OCR 文字识别 API 识别并提取图片中的文字,首先需注册获取 API 调用的 ID 和 key,打开百度AI开放平台,进入控制台中的文字识别应用(需要有百度账号)。 

2、创建一个应用,并进入管理应用,记下 AppID, API Key, Secrect Key,调用 API需用到。 

 

第二步:PyQt5安装和pycharm配置

1.直接使用pip安装,但是需要SIP的支持,所以先安装SIP,再安装pyqt5

pip install sip 
pip install PyQt5

2.安装qt designer,同样使用pip安装

pip install PyQt5-tools

3.配置PyCharm,配置PyCharm是为了在Pycharm里面实现打开qt designer,生成qt文件,方便转换成python文件。

具体步骤可移步查看这篇文章:pyqt5安装与pycharm配置

 

第三步:用qt designer编写界面

新建一个项目,然后在左边窗口部件盒找到需要的控件,拖动到界面编辑区,保存baidu_ocr.ui

 

第四步:对刚才保存的baidu_ocr.ui文件右键选择 External Tools-pyUIC 功能,将QT文件转化为py文件

第五步:编辑相关代码,运行之前请将AK和SK替换为自己的

  1. # -*- coding: utf-8 -*-
  2. '''
  3. author: 神奇的老黄
  4. gtihub: https://github.com/MH-Blog
  5. site: https://magichuang.cn
  6. date: 2019.02.14 23:08
  7. '''
  8. import base64
  9. import json
  10. from PyQt5 import QtCore, QtGui, QtWidgets
  11. import sys
  12. import urllib, urllib.request
  13. import ssl
  14. from PyQt5.QtCore import QSize, Qt
  15. ssl._create_default_https_context = ssl._create_unverified_context
  16. """ 你的 APPID AK SK """
  17. # http://ai.baidu.com/docs#/OCR-Pricing/top 申请地址
  18. # API_KEY 为官网获取的AK, SECRET_KEY 为官网获取的SK
  19. API_KEY = 'API_KEY'
  20. SECRET_KEY = 'SECRET_KEY'
  21. # QT自动生成的UI类
  22. class Ui_Form(object):
  23. def setupUi(self, Form):
  24. # 设置窗体的名称
  25. Form.setObjectName("Form")
  26. # 设置窗体大小
  27. Form.resize(834, 789)
  28. # 新建横向布局
  29. self.horizontalLayoutWidget = QtWidgets.QWidget(Form)
  30. self.horizontalLayoutWidget.setGeometry(QtCore.QRect(40, 30, 251, 61))
  31. self.horizontalLayoutWidget.setObjectName("horizontalLayoutWidget")
  32. self.horizontalLayout = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget)
  33. self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
  34. self.horizontalLayout.setObjectName("horizontalLayout")
  35. self.label = QtWidgets.QLabel(self.horizontalLayoutWidget)
  36. self.label.setObjectName("label")
  37. self.horizontalLayout.addWidget(self.label)
  38. self.comboBox = QtWidgets.QComboBox(self.horizontalLayoutWidget)
  39. # 设置名称
  40. self.comboBox.setObjectName("comboBox")
  41. # 添加子标题有多少分类添加几个
  42. self.comboBox.addItem("")
  43. self.comboBox.addItem("")
  44. self.comboBox.addItem("")
  45. self.comboBox.addItem("")
  46. self.comboBox.addItem("")
  47. self.comboBox.addItem("")
  48. self.comboBox.addItem("")
  49. self.comboBox.addItem("")
  50. self.comboBox.addItem("")
  51. self.comboBox.addItem("")
  52. self.comboBox.addItem("")
  53. # 把下拉选择控件添加到布局容器中
  54. self.horizontalLayout.addWidget(self.comboBox)
  55. # 新建横向布局
  56. self.horizontalLayoutWidget_2 = QtWidgets.QWidget(Form)
  57. self.horizontalLayoutWidget_2.setGeometry(QtCore.QRect(350, 30, 441, 61))
  58. self.horizontalLayoutWidget_2.setObjectName("horizontalLayoutWidget_2")
  59. self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_2)
  60. self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)
  61. self.horizontalLayout_2.setObjectName("horizontalLayout_2")
  62. self.label_2 = QtWidgets.QLabel(self.horizontalLayoutWidget_2)
  63. self.label_2.setObjectName("label_2")
  64. self.horizontalLayout_2.addWidget(self.label_2)
  65. self.lineEdit = QtWidgets.QLineEdit(self.horizontalLayoutWidget_2)
  66. self.lineEdit.setObjectName("lineEdit")
  67. self.horizontalLayout_2.addWidget(self.lineEdit)
  68. # 新建按钮
  69. self.pushButton = QtWidgets.QPushButton(self.horizontalLayoutWidget_2)
  70. self.pushButton.setObjectName("pushButton")
  71. self.horizontalLayout_2.addWidget(self.pushButton)
  72. self.label_3 = QtWidgets.QLabel(Form)
  73. self.label_3.setGeometry(QtCore.QRect(40, 110, 751, 301))
  74. self.label_3.setAutoFillBackground(False)
  75. # 设置黑色边框
  76. self.label_3.setStyleSheet('border-width:1px;border-style:solid;border-color:rgb(0,0,0);')
  77. self.label_3.setObjectName("label_3")
  78. self.horizontalLayoutWidget_3 = QtWidgets.QWidget(Form)
  79. self.horizontalLayoutWidget_3.setGeometry(QtCore.QRect(40, 440, 751, 321))
  80. self.horizontalLayoutWidget_3.setObjectName("horizontalLayoutWidget_3")
  81. self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_3)
  82. self.horizontalLayout_3.setContentsMargins(0, 0, 0, 0)
  83. self.horizontalLayout_3.setObjectName("horizontalLayout_3")
  84. self.verticalLayout_2 = QtWidgets.QVBoxLayout()
  85. self.verticalLayout_2.setObjectName("verticalLayout_2")
  86. self.label_4 = QtWidgets.QLabel(self.horizontalLayoutWidget_3)
  87. self.label_4.setAutoFillBackground(False)
  88. # self.label_4.setStyleSheet("background-color: rgb(253, 188, 49);")
  89. self.label_4.setObjectName("label_4")
  90. self.label_4.setStyleSheet('border-width:1px;border-style:solid;border-color:rgb(0,0,0);')
  91. self.verticalLayout_2.addWidget(self.label_4)
  92. # 新建按钮
  93. self.pushButton_2 = QtWidgets.QPushButton(self.horizontalLayoutWidget_3)
  94. self.pushButton_2.setObjectName("pushButton_2")
  95. self.verticalLayout_2.addWidget(self.pushButton_2, 0, QtCore.Qt.AlignHCenter)
  96. self.horizontalLayout_3.addLayout(self.verticalLayout_2)
  97. # 自动生成的ui控件 处理方法
  98. self.retranslateUi(Form)
  99. # 自动生成的 关联信号槽
  100. QtCore.QMetaObject.connectSlotsByName(Form)
  101. def retranslateUi(self, Form):
  102. _translate = QtCore.QCoreApplication.translate
  103. # 设置窗体内容
  104. Form.setWindowTitle(_translate("Form", "百度图片识别程序"))
  105. # 设置文字控件显示内容
  106. self.label.setText(_translate("Form", "识别类型:"))
  107. # 设置下拉控件选项内容
  108. self.comboBox.setItemText(0, _translate("Form", "银行卡"))
  109. self.comboBox.setItemText(1, _translate("Form", "植物"))
  110. self.comboBox.setItemText(2, _translate("Form", "动物"))
  111. self.comboBox.setItemText(3, _translate("Form", "通用票据"))
  112. self.comboBox.setItemText(4, _translate("Form", "营业执照"))
  113. self.comboBox.setItemText(5, _translate("Form", "身份证"))
  114. self.comboBox.setItemText(6, _translate("Form", "车牌号"))
  115. self.comboBox.setItemText(7, _translate("Form", "驾驶证"))
  116. self.comboBox.setItemText(8, _translate("Form", "行驶证"))
  117. self.comboBox.setItemText(9, _translate("Form", "车型"))
  118. self.comboBox.setItemText(10, _translate("Form", "Logo"))
  119. self.label_2.setText(_translate("Form", "图片路径:"))
  120. self.pushButton.setText(_translate("Form", "选择"))
  121. self.label_3.setText(_translate("Form", "<html><head/><body><p align=\"center\">此处显示照片</p></body></html>"))
  122. self.label_4.setText(_translate("Form", "<html><head/><body><p align=\"center\">此处显示结果</p></body></html>"))
  123. self.pushButton_2.setText(_translate("Form", "复制到剪贴板"))
  124. # 为 选择图片 按钮添加点击事件
  125. self.pushButton.clicked.connect(self.openFile)
  126. # 为 复制到剪贴板 按钮添加点击时间
  127. self.pushButton_2.clicked.connect(self.copyText)
  128. # 复制到剪贴板
  129. def copyText(self):
  130. clipboard = QtWidgets.QApplication.clipboard()
  131. clipboard.setText(self.label_4.text())
  132. # QMessageBox.about(self,'关于','这是一个关于消息对话框!')
  133. msgBox = QtWidgets.QMessageBox(QtWidgets.QMessageBox.NoIcon, '提醒', '识别内容已成功复制到剪贴板 !')
  134. msgBox.exec()
  135. # 打开文件选择对话框方法
  136. def openFile(self):
  137. # 启动选择文件对话框,查找jpg以及png图片
  138. self.download_path = QtWidgets.QFileDialog.getOpenFileName(self.horizontalLayoutWidget, '选择要识别的图片', '',
  139. 'Image File (*.jpg *.jpeg *.png)')
  140. # 判断是否选择图片
  141. if not self.download_path[0].strip():
  142. pass
  143. else:
  144. # 将路径显示到地址栏中
  145. self.lineEdit.setText(self.download_path[0])
  146. # 将图片显示到图片展示区
  147. pixmap = QtGui.QPixmap(self.download_path[0])
  148. # self.label_3.setPixmap(pixmap)
  149. # 等比例缩放图片
  150. scaredPixmap = pixmap.scaled(QSize(311, 301), aspectRatioMode=Qt.KeepAspectRatio)
  151. # 设置图片
  152. self.label_3.setPixmap(scaredPixmap)
  153. # 判断选择的类型 根据类型做相应的图片处理
  154. self.label_3.show()
  155. # 判断选择的类型
  156. self.typeTp()
  157. # 判断选择的类型 进行相应处理
  158. def typeTp(self):
  159. # 银行卡识别
  160. if self.comboBox.currentIndex() == 0:
  161. self.get_bankcard(self.get_token())
  162. pass
  163. # 植物识别
  164. elif self.comboBox.currentIndex() == 1:
  165. self.get_plant(self.get_token())
  166. pass
  167. # 动物识别
  168. elif self.comboBox.currentIndex() == 2:
  169. self.get_animal(self.get_token())
  170. pass
  171. # 通用票据识别识别
  172. elif self.comboBox.currentIndex() == 3:
  173. self.get_vat_invoice(self.get_token())
  174. pass
  175. # 营业执照识别
  176. elif self.comboBox.currentIndex() == 4:
  177. self.get_business_licensev(self.get_token())
  178. pass
  179. # 身份证识别
  180. elif self.comboBox.currentIndex() == 5:
  181. self.get_idcard(self.get_token())
  182. pass
  183. # 车牌号识别
  184. elif self.comboBox.currentIndex() == 6:
  185. self.get_license_plate(self.get_token())
  186. pass
  187. # 驾驶证识别
  188. elif self.comboBox.currentIndex() == 7:
  189. self.get_driving_license(self.get_token())
  190. pass
  191. # 行驶证识别
  192. elif self.comboBox.currentIndex() == 8:
  193. self.get_vehicle_license(self.get_token())
  194. pass
  195. # 车型识别
  196. elif self.comboBox.currentIndex() == 9:
  197. self.get_car(self.get_token())
  198. pass
  199. # Logo识别
  200. elif self.comboBox.currentIndex() == 10:
  201. self.get_logo(self.get_token())
  202. pass
  203. pass
  204. # 获取token
  205. def get_token(self):
  206. # client_id 为官网获取的AK, client_secret 为官网获取的SK
  207. host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + API_KEY + '&client_secret=' + SECRET_KEY
  208. # 发送请求
  209. request = urllib.request.Request(host)
  210. # 添加请求头
  211. request.add_header('Content-Type', 'application/json; charset=UTF-8')
  212. # 获取返回内容
  213. response = urllib.request.urlopen(request)
  214. # 读取返回内容
  215. content = response.read()
  216. # 判断内容是否为空
  217. if (content):
  218. # 打印内容
  219. print(content)
  220. # 打印token
  221. print(json.loads(content)['access_token'])
  222. # 使用json解析出token 设置token
  223. self.access_token = json.loads(content)['access_token']
  224. # 返回token
  225. return self.access_token
  226. # 0 银行卡识别
  227. def get_bankcard(self, access_token):
  228. request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/bankcard"
  229. # 二进制方式打开图片文件
  230. f = self.get_file_content(self.download_path[0])
  231. img = base64.b64encode(f)
  232. params = {"image": img}
  233. params = urllib.parse.urlencode(params).encode('utf-8')
  234. request_url = request_url + "?access_token=" + access_token
  235. request = urllib.request.Request(url=request_url, data=params)
  236. request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  237. response = urllib.request.urlopen(request)
  238. content = response.read()
  239. if content:
  240. # 解析返回数据
  241. bankcards = json.loads(content)
  242. # 输出返回结果
  243. strover = '识别结果:\n'
  244. # 捕捉异常判断是否正确返回信息
  245. try:
  246. # 判断银行卡类型
  247. if bankcards['result']['bank_card_type'] == 0:
  248. bank_card_type = '不能识别'
  249. elif bankcards['result']['bank_card_type'] == 1:
  250. bank_card_type = '借记卡'
  251. elif bankcards['result']['bank_card_type'] == 2:
  252. bank_card_type = '信用卡'
  253. strover += ' 卡号:{} \n 银行:{} \n 类型:{} \n'.format(bankcards['result']['bank_card_number'],
  254. bankcards['result']['bank_name'], bank_card_type)
  255. # 错误的时候提示错误原因
  256. except BaseException:
  257. error_msg = bankcards['error_msg']
  258. strover += ' 错误:\n {} \n '.format(error_msg)
  259. # 设置识别显示结果
  260. self.label_4.setText(strover)
  261. # 1 植物识别
  262. def get_plant(self, access_token):
  263. request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/plant"
  264. # 二进制方式打开图片文件
  265. f = self.get_file_content(self.download_path[0])
  266. # 转换图片
  267. img = base64.b64encode(f)
  268. # 拼接图片参数
  269. params = {"image": img}
  270. params = urllib.parse.urlencode(params).encode('utf-8')
  271. # 请求地址
  272. request_url = request_url + "?access_token=" + access_token
  273. # 发送请求传递图片参数
  274. request = urllib.request.Request(url=request_url, data=params)
  275. # 添加访问头部
  276. request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  277. # 接收返回内容
  278. response = urllib.request.urlopen(request)
  279. # 读取返回内容
  280. content = response.read()
  281. # 内容判断
  282. if content:
  283. plants = json.loads(content)
  284. strover = '识别结果:\n'
  285. try:
  286. i = 1
  287. for plant in plants['result']:
  288. strover += '{} 植物名称:{} \n'.format(i, plant['name'])
  289. i += 1
  290. except BaseException:
  291. error_msg = plants['error_msg']
  292. strover += ' 错误:\n {} \n '.format(error_msg)
  293. self.label_4.setText(strover)
  294. # 2 动物识别
  295. def get_animal(self, access_token):
  296. request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/animal"
  297. # 二进制方式打开图片文件
  298. f = self.get_file_content(self.download_path[0])
  299. img = base64.b64encode(f)
  300. params = {"image": img, "top_num": 6}
  301. params = urllib.parse.urlencode(params).encode('utf-8')
  302. request_url = request_url + "?access_token=" + access_token
  303. request = urllib.request.Request(url=request_url, data=params)
  304. request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  305. response = urllib.request.urlopen(request)
  306. content = response.read()
  307. if content:
  308. animals = json.loads(content)
  309. strover = '识别结果:\n'
  310. try:
  311. i = 1
  312. for animal in animals['result']:
  313. strover += '{} 动物名称:{} \n'.format(i, animal['name'])
  314. i += 1
  315. except BaseException:
  316. error_msg = animals['error_msg']
  317. strover += ' 错误:\n {} \n '.format(error_msg)
  318. self.label_4.setText(strover)
  319. # 3 通用票据识别
  320. def get_vat_invoice(self, access_token):
  321. request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/receipt"
  322. # 二进制方式打开图片文件
  323. f = self.get_file_content(self.download_path[0])
  324. img = base64.b64encode(f)
  325. params = {"image": img}
  326. params = urllib.parse.urlencode(params).encode('utf-8')
  327. request_url = request_url + "?access_token=" + access_token
  328. request = urllib.request.Request(url=request_url, data=params)
  329. request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  330. response = urllib.request.urlopen(request)
  331. content = response.read()
  332. if content:
  333. receipts = json.loads(content)
  334. strover = '识别结果:\n'
  335. try:
  336. words_result = receipts['words_result']
  337. for word_result in words_result:
  338. # 票据内容
  339. InvoiceType = word_result['words']
  340. strover += ' {} '.format(InvoiceType)
  341. except BaseException:
  342. error_msg = receipts['error_msg']
  343. strover += ' 错误:\n {} \n '.format(error_msg)
  344. self.label_4.setText(strover)
  345. # 4 营业执照识别
  346. def get_business_licensev(self, access_token):
  347. request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/business_license"
  348. # 二进制方式打开图片文件
  349. f = self.get_file_content(self.download_path[0])
  350. img = base64.b64encode(f)
  351. params = {"image": img}
  352. params = urllib.parse.urlencode(params).encode('utf-8')
  353. request_url = request_url + "?access_token=" + access_token
  354. request = urllib.request.Request(url=request_url, data=params)
  355. request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  356. response = urllib.request.urlopen(request)
  357. content = response.read()
  358. if content:
  359. business_licenses = json.loads(content)
  360. strover = '识别结果:\n'
  361. try:
  362. words_result = business_licenses['words_result']
  363. # 单位名称
  364. Unit_name = words_result['单位名称']['words']
  365. strover += ' 单位名称:\n {} \n '.format(Unit_name)
  366. # 法人
  367. legal_person = words_result['法人']['words']
  368. strover += ' 法人:{} \n '.format(legal_person)
  369. # 有效期
  370. Term_of_validity = words_result['有效期']['words']
  371. strover += ' 有效期:{} \n '.format(Term_of_validity)
  372. # 证件编号
  373. ID_number = words_result['证件编号']['words']
  374. strover += ' 证件编号:{} \n '.format(ID_number)
  375. # 社会信用代码
  376. Social_Credit_Code = words_result['社会信用代码']['words']
  377. strover += ' 社会信用代码:{} \n '.format(Social_Credit_Code)
  378. # 地址
  379. address = words_result['地址']['words']
  380. strover += ' 地址:\n{}\n '.format(address)
  381. except BaseException:
  382. error_msg = business_licenses['error_msg']
  383. strover += ' 错误:\n {} \n '.format(error_msg)
  384. self.label_4.setText(strover)
  385. # 5 身份证识别
  386. def get_idcard(self, access_token):
  387. request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard"
  388. # 二进制方式打开图片文件
  389. f = self.get_file_content(self.download_path[0])
  390. img = base64.b64encode(f)
  391. params = {"image": img, "id_card_side": "front"}
  392. params = urllib.parse.urlencode(params).encode('utf-8')
  393. request_url = request_url + "?access_token=" + access_token
  394. request = urllib.request.Request(url=request_url, data=params)
  395. request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  396. response = urllib.request.urlopen(request)
  397. content = response.read()
  398. if content:
  399. idcards = json.loads(content)
  400. strover = '识别结果:\n'
  401. try:
  402. words_result = idcards['words_result']
  403. # 公民身份号码
  404. Citizenship_number = words_result['公民身份号码']['words']
  405. strover += ' 公民身份号码:\n{} \n '.format(Citizenship_number)
  406. # 民族
  407. Nation = words_result['民族']['words']
  408. strover += ' 民族:{} \n '.format(Nation)
  409. # 姓名
  410. Full_name = words_result['姓名']['words']
  411. strover += ' 姓名:{} \n '.format(Full_name)
  412. # 住址
  413. address = words_result['住址']['words']
  414. strover += ' 住址:\n{} \n '.format(address)
  415. except BaseException:
  416. error_msg = idcards['error_msg']
  417. strover += ' 错误:\n {} \n '.format(error_msg)
  418. # 显示识别结果
  419. self.label_4.setText(strover)
  420. # 6 车牌号识别
  421. def get_license_plate(self, access_token):
  422. request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate"
  423. # 二进制方式打开图片文件
  424. f = self.get_file_content(self.download_path[0])
  425. img = base64.b64encode(f)
  426. params = {"image": img}
  427. params = urllib.parse.urlencode(params).encode('utf-8')
  428. request_url = request_url + "?access_token=" + access_token
  429. request = urllib.request.Request(url=request_url, data=params)
  430. request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  431. response = urllib.request.urlopen(request)
  432. content = response.read()
  433. if content:
  434. license_plates = json.loads(content)
  435. strover = '识别结果:\n'
  436. try:
  437. words_result = license_plates['words_result']
  438. # 车牌号
  439. number = words_result['number']
  440. strover += ' 车牌号:{} \n '.format(number)
  441. except BaseException:
  442. error_msg = license_plates['error_msg']
  443. strover += ' 错误:\n {} \n '.format(error_msg)
  444. self.label_4.setText(strover)
  445. # 7 驾驶证识别
  446. def get_driving_license(self, access_token):
  447. request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/driving_license"
  448. # 二进制方式打开图片文件
  449. f = self.get_file_content(self.download_path[0])
  450. img = base64.b64encode(f)
  451. params = {"image": img}
  452. params = urllib.parse.urlencode(params).encode('utf-8')
  453. request_url = request_url + "?access_token=" + access_token
  454. request = urllib.request.Request(url=request_url, data=params)
  455. request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  456. response = urllib.request.urlopen(request)
  457. content = response.read()
  458. if content:
  459. driving_licenses = json.loads(content)
  460. strover = '识别结果:\n'
  461. try:
  462. words_result = driving_licenses['words_result']
  463. # 证号
  464. Citizenship_number = words_result['证号']['words']
  465. strover += ' 证号: {} \n '.format(Citizenship_number)
  466. # 准驾车型
  467. Full_name = words_result['准驾车型']['words']
  468. strover += ' 准驾车型:{} \n '.format(Full_name)
  469. # 姓名
  470. name = words_result['姓名']['words']
  471. strover += ' 姓名: {} \n '.format(name)
  472. # 国籍
  473. nationality = words_result['国籍']['words']
  474. strover += ' 国籍: {} \n '.format(nationality)
  475. # 出生日期
  476. date_of_birth = words_result['出生日期']['words']
  477. strover += ' 出生日期: {} \n '.format(date_of_birth)
  478. # 性别
  479. sex = words_result['性别']['words']
  480. strover += ' 性别: {} \n '.format(sex)
  481. # 初次领证日期
  482. first_certificate_date = words_result['初次领证日期']['words']
  483. strover += ' 初次领证日期: {} \n '.format(first_certificate_date)
  484. # 有效期限
  485. Nation = words_result['有效期限']['words']
  486. # 到期日期
  487. to = words_result['至']['words']
  488. strover += ' 有效期限:{}至{}\n '.format(Nation, to)
  489. # 住址
  490. address = words_result['住址']['words']
  491. strover += ' 住址:\n{} \n '.format(address)
  492. except BaseException:
  493. error_msg = driving_licenses['error_msg']
  494. strover += ' 错误:\n {} \n '.format(error_msg)
  495. self.label_4.setText(strover)
  496. # 8 行驶证识别
  497. def get_vehicle_license(self, access_token):
  498. request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/vehicle_license"
  499. # 二进制方式打开图片文件
  500. f = self.get_file_content(self.download_path[0])
  501. img = base64.b64encode(f)
  502. params = {"image": img}
  503. params = urllib.parse.urlencode(params).encode('utf-8')
  504. request_url = request_url + "?access_token=" + access_token
  505. request = urllib.request.Request(url=request_url, data=params)
  506. request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  507. response = urllib.request.urlopen(request)
  508. content = response.read()
  509. if content:
  510. vehicle_licenses = json.loads(content)
  511. strover = '识别结果:\n'
  512. try:
  513. words_result = vehicle_licenses['words_result']
  514. # 品牌型号
  515. brand_model = words_result['品牌型号']['words']
  516. strover += ' 品牌型号: {} \n '.format(brand_model)
  517. # 发证日期
  518. date_of_certification = words_result['发证日期']['words']
  519. strover += ' 发证日期:{} \n '.format(date_of_certification)
  520. # 使用性质
  521. use_nature = words_result['使用性质']['words']
  522. strover += ' 使用性质: {} \n '.format(use_nature)
  523. # 发动机号码
  524. engine_number = words_result['发动机号码']['words']
  525. strover += ' 发动机号码: {} \n '.format(engine_number)
  526. # 注册日期
  527. date_of_registration = words_result['注册日期']['words']
  528. strover += ' 注册日期: {} \n '.format(date_of_registration)
  529. # 号牌号码
  530. number_number = words_result['号牌号码']['words']
  531. strover += ' 号牌号码: {} \n '.format(number_number)
  532. # 车辆识别代号
  533. vehicle_identification = words_result['车辆识别代号']['words']
  534. strover += ' 车辆识别代号: {} \n '.format(vehicle_identification)
  535. # 车辆类型
  536. vehicle_type = words_result['车辆类型']['words']
  537. strover += ' 车辆类型: {} \n '.format(vehicle_type)
  538. # 所有人
  539. owner = words_result['所有人']['words']
  540. strover += ' 所有人:\n{} \n '.format(owner)
  541. # 住址
  542. address = words_result['住址']['words']
  543. strover += ' 住址:\n{} \n '.format(address)
  544. except BaseException:
  545. error_msg = vehicle_licenses['error_msg']
  546. strover += ' 错误:\n {} \n '.format(error_msg)
  547. self.label_4.setText(strover)
  548. # 9 获取车型信息
  549. def get_car(self, access_token):
  550. request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/car"
  551. # 二进制方式打开图片文件
  552. f = self.get_file_content(self.download_path[0])
  553. img = base64.b64encode(f)
  554. params = {"image": img, "top_num": 5}
  555. params = urllib.parse.urlencode(params).encode('utf-8')
  556. request_url = request_url + "?access_token=" + access_token
  557. request = urllib.request.Request(url=request_url, data=params)
  558. request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  559. response = urllib.request.urlopen(request)
  560. content = response.read()
  561. if content:
  562. cars = json.loads(content)
  563. strover = '识别结果:\n'
  564. try:
  565. i = 1
  566. for car in cars['result']:
  567. strover += '{} 车型:{} \n 年份:{} \n'.format(i, car['name'], car['year'])
  568. i += 1
  569. except BaseException:
  570. error_msg = cars['error_msg']
  571. strover += ' 错误:\n {} \n '.format(error_msg)
  572. self.label_4.setText(strover)
  573. # 10 获取logo信息
  574. def get_logo(self, access_token):
  575. request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v2/logo"
  576. # 二进制方式打开图片文件
  577. f = self.get_file_content(self.download_path[0])
  578. img = base64.b64encode(f)
  579. params = {"custom_lib": False, "image": img}
  580. params = urllib.parse.urlencode(params).encode('utf-8')
  581. request_url = request_url + "?access_token=" + access_token
  582. request = urllib.request.Request(url=request_url, data=params)
  583. request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  584. response = urllib.request.urlopen(request)
  585. content = response.read()
  586. if content:
  587. logos = json.loads(content)
  588. strover = '识别结果:\n'
  589. try:
  590. i = 1
  591. for logo in logos['result']:
  592. strover += '{} Logo名称:{} \n'.format(i, logo['name'])
  593. i += 1
  594. except BaseException:
  595. error_msg = logos['error_msg']
  596. strover += ' 错误:\n {} \n '.format(error_msg)
  597. self.label_4.setText(strover)
  598. # 读取图片
  599. def get_file_content(self, filePath):
  600. with open(filePath, 'rb') as fp:
  601. return fp.read()
  602. if __name__ == '__main__':
  603. app = QtWidgets.QApplication(sys.argv)
  604. MainWindow = QtWidgets.QMainWindow()
  605. ui = Ui_Form()
  606. ui.setupUi(MainWindow)
  607. MainWindow.show()
  608. sys.exit(app.exec_())

为了方便测试,已经将所有项目文件和所需的测试图片打包上传了

下载地址:百度图像自动识别

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/652848
推荐阅读
相关标签
  

闽ICP备14008679号