这里我是用百度提供的行驶证识别API,先上百度API镇贴地址:https://cloud.baidu.com/product/ocr
接下来是官网给的官方sdk中方法:
public void sample(AipOcr client) {
// 传入可选参数调用接口
HashMap<String, String> options = new HashMap<String, String>();
options.put("detect_direction", "true");
options.put("accuracy", "normal");
// 参数为本地图片路径
String image = "test.jpg";
JSONObject res = client.vehicleLicense(image, options);
System.out.println(res.toString(2));
// 参数为本地图片二进制数组
byte[] file = readImageFile(image);
res = client.vehicleLicense(file, options);
System.out.println(res.toString(2));
}
官网给的方法是针对于本地的图片进行识别,我当初需要开发的是前端上传图片,图片不需要保存,直接识别
所以我就用了第二种方法,参数与本地图片二进制数组,根据接收上传到的图片,将图片转成二进制数组进行API调用与识别
接下来
上我的代码
public void dentificationi(@RequestParam(value = "file", required = false) MultipartFile file) {
try {
if (file != null) {
byte[] flies = file.getBytes();//获取图片的二进制数组
HashMap<String, String> options = new HashMap<String, String>();
options.put("detect_direction", "true");
options.put("accuracy", "normal");
String fileName = file.getOriginalFilename();// 文件原名称
// 将文件类型截出来,判断文件类型
String type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
if (type != null) {// 判断文件类型是否为空
//这里是规定图片的类型,必须是png和jpg,我这里规定的是图片的后缀,如果需要上传别的类型文件,可以自行更改
if ("BMP".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase())) {
// 转存文件到指定的路径
AipOcr client = new AipOcr(AipOcrConst.APPID, AipOcrConst.APIKEY, AipOcrConst.SECRETKEY);
JSONObject res = client.vehicleLicense(flies, options);
// 截取车牌号
JSONObject resultJsonObject = res.getJSONObject("words_result");
String engineNumber = resultJsonObject.getJSONObject("发动机号码").getString("words");//发动机号码
String plateNumber = resultJsonObject.getJSONObject("号牌号码").getString("words");
String owner = resultJsonObject.getJSONObject("所有人").getString("words");//所有人
String vehicleIdentificationNumber = resultJsonObject.getJSONObject("车辆识别代号").getString("words");//车辆识别代号
log.info("<--engineNumber-->"+engineNumber+"<--plateNumber-->"+plateNumber+"<--owner-->"+owner);
}
} else {
log.error("文件类型错误");
}
} else {
log.error("文件类型为空");
}
}
} catch (Exception e) {
log.error("行驶证识别失败:" + e.getMessage());
}
}
这样就大功告成了。。。