【百度大脑新品体验】行驶证识别

一、功能介绍

对机动车行驶证主页及副页所有21个字段进行结构化识别,包括号牌号码、车辆类型、所有人、品牌型号、车辆识别代码、发动机号码、核定载人数、质量、检验记录等。

具体功能说明,请参考官方说明文档(行驶证识别):https://ai.baidu.com/docs#/OCR-API/3fa9e937

二、应用场景

1、司机身份认证
使用行驶证和驾驶证识别技术,实现对用户身份信息和驾驶证信息的结构化识别和录入,可应用于网约车或货车司机身份审查等场景,有效提升信息录入效率,降低用户输入成本,提升用户使用体验。
2、车主信息服务
使用驾驶证和行驶证识别技术,实现对车主和车辆信息的结构化识别和录入,可应用于个性化信息推送、违章信息查询等场景,有效降低用户输入成本,为用户提供信息推送和查询服务,提升用户使用体验。
3、汽车后市场服务
使用汽车场景下多种卡证和票据识别服务,实现对车主及车辆信息的自动识别和录入,应用于新能源汽车国家补贴申报、汽车金融保险、维修保养等后市场服务场景,能够有效提高相关信息输入效率,降低车主输入成本,提升用户使用体验。

三、使用攻略

说明:本文采用C# 语言,开发环境为.Net Core 2.1,采用在线API接口方式实现。

(1)、登陆 百度智能云-管理中心 创建 “文字识别”应用,获取 “API Key ”和 “Secret Key”:https://console.bce.baidu.com/ai/?_=1566309958051&fromai=1#/ai/ocr/overview/index
(2)、根据 API Key 和 Secret Key 获取 AccessToken。

    /// 
    /// 获取百度access_token
    /// 
    /// API Key
    /// Secret Key
    /// 
    public static string GetAccessToken(string clientId, string clientSecret)
    {
        string authHost = "https://aip.baidubce.com/oauth/2.0/token";
        HttpClient client = new HttpClient();
        List> paraList = new List>();
        paraList.Add(new KeyValuePair("grant_type", "client_credentials"));
        paraList.Add(new KeyValuePair("client_id", clientId));
        paraList.Add(new KeyValuePair("client_secret", clientSecret)); 

        HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
        string result = response.Content.ReadAsStringAsync().Result;
        JObject jo = (JObject)JsonConvert.DeserializeObject(result);

        string token = jo["access_token"].ToString();
        return token;
    }

(3)、调用API接口获取识别结果

1、在Startup.cs 文件 的 Configure(IApplicationBuilder app, IHostingEnvironment env) 方法中开启虚拟目录映射功能:

        string webRootPath = HostingEnvironment.WebRootPath;//wwwroot目录

        app.UseStaticFiles(new StaticFileOptions
        {
            FileProvider = new PhysicalFileProvider(
                Path.Combine(webRootPath, "Uploads", "BaiduAIs")),
            RequestPath = "/BaiduAIs"
        });

2、 建立BodySearch.cshtml文件

2.1前端页面说明

由于html代码无法原生显示,只能简单说明一下:

主要是一个form表单,需要设置属性enctype=“multipart/form-data”,否则无法上传图片;

form表单里面有两个控件:

一个Input:type=“file”,asp-for=“FileUpload” ,上传图片用;

一个Input:type=“submit”,asp-page-handler=“VehicleLicense” ,提交并返回识别结果。

一个img:src="@Model.curPath",显示识别的图片。

最后显示后台 msg 字符串列表信息。

2.2 后台代码

    [BindProperty]
    public IFormFile FileUpload { get; set; }
    [BindProperty]
    public string ImageUrl { get; set; }
    private readonly IHostingEnvironment HostingEnvironment;
    public List msg = new List();
    public string curPath { get; set; }

    public OCRSearchModel(IHostingEnvironment hostingEnvironment)
    {
        HostingEnvironment = hostingEnvironment;
    }


    public async Task OnPostVehicleLicenseAsync()
    {
        if (FileUpload is null)
        {
            ModelState.AddModelError(string.Empty, "请先选择本地图片!");
        }
        if (!ModelState.IsValid)
        {
            return Page();
        }
        msg = new List();

        string webRootPath = HostingEnvironment.WebRootPath;//wwwroot目录
        string fileDir = Path.Combine(webRootPath, "Uploads//BaiduAIs//");
        string imgName =  await UploadFile(FileUpload, fileDir);

        string fileName = Path.Combine(fileDir, imgName);
        string imgBase64 = Common.GetFileBase64(fileName);
        curPath = Path.Combine("/BaiduAIs/", imgName);

        string result = GetOCRJson(imgBase64, “你的API KEY”, “你的SECRET KEY”);
        JObject jo = (JObject)JsonConvert.DeserializeObject(result);

        try
        {
            msg.Add("行驶证识别结果:\n");
            int number = int.Parse(jo["words_result_num"].ToString());
            msg.Add("识别信息数:" + number);
            msg.Add("品牌型号:" + jo["words_result"]["品牌型号"]["words"].ToString());
            msg.Add("发证日期:" + jo["words_result"]["发证日期"]["words"].ToString());
            msg.Add("使用性质:" + jo["words_result"]["使用性质"]["words"].ToString());
            msg.Add("发动机号码:" + jo["words_result"]["发动机号码"]["words"].ToString());
            msg.Add("号牌号码:" + jo["words_result"]["号牌号码"]["words"].ToString());
            msg.Add("所有人:" + jo["words_result"]["所有人"]["words"].ToString());
            msg.Add("住址:" + jo["words_result"]["住址"]["words"].ToString());
            msg.Add("注册日期:" + jo["words_result"]["注册日期"]["words"].ToString());
            msg.Add("车辆识别代号:" + jo["words_result"]["车辆识别代号"]["words"].ToString());
            msg.Add("车辆类型:" + jo["words_result"]["车辆类型"]["words"].ToString());
        }
        catch (Exception e)
        {
            msg.Add(result);
        }
        return Page();
    }

    /// 
    /// 上传文件,返回文件名
    /// 
    /// 文件上传控件
    /// 文件绝对路径
    public static async Task UploadFile(IFormFile formFile, string fileDir)
    {
        if (!Directory.Exists(fileDir))
        {
            Directory.CreateDirectory(fileDir);
        }
        string extension = Path.GetExtension(formFile.FileName);
        string imgName = Guid.NewGuid().ToString("N") + extension;
        var filePath = Path.Combine(fileDir, imgName);



        using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
        {
            await formFile.CopyToAsync(fileStream);
        }

        return imgName;
    }

    /// 
    /// 返回图片的base64编码
    /// 
    /// 文件绝对路径名称
    /// 
    public static String GetFileBase64(string fileName)
    {
        FileStream filestream = new FileStream(fileName, FileMode.Open);
        byte[] arr = new byte[filestream.Length];
        filestream.Read(arr, 0, (int)filestream.Length);
        string baser64 = Convert.ToBase64String(arr);
        filestream.Close();
        return baser64;
    }

    /// 
    /// 文字识别Json字符串
    /// 
    /// 图片base64编码
    /// API Key
    /// Secret Key
    /// 
    public static string GetOCRJson(string strbaser64, string clientId, string clientSecret)
    {
        string token = GetAccessToken(clientId, clientSecret);
        string host = "https://aip.baidubce.com/rest/2.0/ocr/v1/vehicle_license?access_token=" + token;
        Encoding encoding = Encoding.Default;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
        request.Method = "post";
        request.ContentType = "application/x-www-form-urlencoded";
        request.KeepAlive = true;
        string str = "image=" + HttpUtility.UrlEncode(strbaser64);
        byte[] buffer = encoding.GetBytes(str);
        request.ContentLength = buffer.Length;
        request.GetRequestStream().Write(buffer, 0, buffer.Length);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
        string result = reader.ReadToEnd();
        return result;
    }

四、效果测试

1、页面:
在这里插入图片描述

2、识别结果:

2.1
在这里插入图片描述

2.2
在这里插入图片描述

2.3
在这里插入图片描述

四、测试结果及建议

从上面的测试结果可以发现,百度文字识别对行驶证的识别结果相当准确,各种字段基本上能够完全正确识别,若能连接交警的行驶证数据库,可以直接扫描行驶证获取当前行驶证的司机身份,提升交警的司机身份审查效率。或者用到汽车售后服务中心,直接扫描登记、查询司机信息,可大幅提升司机信息的录入、查询效率,减少售后服务人员的工作量。

另外,在识别速度方面,目前大概1-2秒左右,应该还有提升的空间。

发布了10 篇原创文章 · 获赞 4 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_45449540/article/details/103633751