赞
踩
本文介绍了如何使用百度AI开放平台获取token;以及如何调用百度API接口,请求车牌识别;以及对结果进行解析,并根据百度返回的坐标值画出车牌所在位置的矩形框。
通过如下代码获取token。将获取到的API key 替换下面代码中client_id的, Secret Key替换client_secret。
import requests
# client_id 为官网获取的AK, client_secret 为官网获取的SK
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=【client_id】&client_secret=【client_secret】'
headers = {'Content-Type': 'application/json; charset=UTF-8'}
res = requests.get(url=host, headers=headers).json()
print(res['access_token'])
调用百度API接口,请求车牌识别。
例如上述过程中,产生的access_token为’24.4a29644749eb522b170e6d15bb47ce66.2592000’,将其替换data中的access_token
# 请求百度车牌识别 def request_baidu_lpr(img_file): url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate' data = {} data['access_token'] = '24.4a29644749eb522b170e6d15bb47ce66.2592000' # 读取图片 file = open(img_file, 'rb') image = file.read() file.close() data['image'] = base64.b64encode(image) headers = { "Content-Type": "application/x-www-form-urlencoded" } res = requests.post(url=url, headers=headers, data=data) return res.json()
经过第二步得到的是json文件,需要对其进行解析,同时也需要根据百度返回的坐标值画出矩形框。
# 解析baidu识别结果 # 画出矩形框 def parse_baidu_result(result, img_file): result_lpr = result['words_result']['number'] print('baidu识别结果', result_lpr) probability = result['words_result']['probability'] import numpy as np probability_total = np.sum(probability) result_confidence = probability_total / len(probability) # 坐标位置 rect = result['words_result']['vertexes_location'] pos_1 = (rect[0]['x']-1, rect[0]['y']-12) pos_2 = (rect[2]['x']+3, rect[2]['y']+12) # 车牌所在位置画矩形框 import cv2 image = cv2.imread(img_file) cv2.rectangle(image, pos_1, pos_2, (0, 0, 255), 4) # 保存车牌文件到指定目录 t = str(time.time()) img_url = './static/images/lpr/lpr_result' + t + '.jpg' cv2.imwrite(img_url, image) # 返回车牌识别结果、置信度、图像存放路径 return result_lpr, result_confidence, img_url
上诉2、3步骤的上层调用情况:
result = request_baidu_lpr(img)
result_lpr, confidence, img_url = parse_baidu_result(result, img)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。