【人像特效】 营业执照识别
让天涯 发布于2020-10 浏览:4143 回复:0
0
收藏

百度的营业执照识别技术支持对不同版式营业执照的证件编号、社会信用代码、单位名称、地址、法人、类型、成立日期、有效日期、经营范围等关键字段进行结构化识别。

本文就如何调用营业执照识别技术做个简单的教程。

一、使用攻略

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

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

(2)接口文档

文档地址:https://ai.baidu.com/ai-doc/OCR/sk3h7y3zs

接口描述:

支持对不同版式营业执照的证件编号、社会信用代码、单位名称、地址、法人、类型、成立日期、有效日期、经营范围等关键字段进行结构化识别。

请求说明

HTTP方法:POST
请求URL:https://aip.baidubce.com/rest/2.0/ocr/v1/business_license
URL参数:

Header如下:

Body中放置请求参数,参数详情如下:
请求参数

返回说明
返回参数

返回示例:

{
    "log_id": 490058765,
    "words_result": {
        "社会信用代码": {
            "words": "10440119MA06M8503",
            "location": {
                "top": 296,
                "left": 237,
                "width": 178,
                "height": 18
            }
        },
        "组成形式": {
            "words": "无",
            "location": {
                "top": -1,
                "left": -1,
                "width": 0,
                "height": 0
            }
        },
        "经营范围": {
            "words": "商务服务业",
            "location": {
                "top": 587,
                "left": 378,
                "width": 91,
                "height": 18
            }
        },
        "成立日期": {
            "words": "2019年01月01日",
            "location": {
                "top": 482,
                "left": 1045,
                "width": 119,
                "height": 19
            }
        },
        "法人": {
            "words": "方平",
            "location": {
                "top": 534,
                "left": 377,
                "width": 39,
                "height": 19
            }
        },
        "注册资本": {
            "words": "200万元",
            "location": {
                "top": 429,
                "left": 1043,
                "width": 150,
                "height": 19
            }
        },
        "证件编号": {
            "words": "921MA190538210301",
            "location": {
                "top": 216,
                "left": 298,
                "width": 146,
                "height": 16
            }
        },
        "地址": {
            "words": "广州市",
            "location": {
                "top": 585,
                "left": 1041,
                "width": 55,
                "height": 19
            }
        },
        "单位名称": {
            "words": "有限公司",
            "location": {
                "top": 429,
                "left": 382,
                "width": 72,
                "height": 19
            }
        },
        "有效期": {
            "words": "长期",
            "location": {
                "top": 534,
                "left": 1045,
                "width": 0,
                "height": 0
            }
        },
        "类型": {
            "words": "有限责任公司(自然人投资或控股)",
            "location": {
                "top": 482,
                "left": 382,
                "width": 260,
                "height": 18
            }
        }
    },
    "log_id": 1310106134421438464,
    "words_result_num": 11
}

(3)源码共享

(3-1)根据 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-2)调用API接口获取识别结果

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

string webRootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");//wwwroot目录

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

(3-2-2) 建立Index.cshtml文件

(3-2-2-1)前台代码:

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

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

form表单里面有几个控件:

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

一个Input:type="submit",asp-page-handler="BusinessLicense" ,提交请求。

一个img:src="@Model.curPath",显示需要识别的营业执照图片。

最后显示后台 msg 字符串列表信息,如果需要输出原始Html代码,则需要使用@Html.Raw()函数。

(3-2-2-2) 后台代码: 

主程序代码:

[BindProperty]
public IFormFile FileUpload { get; set; }
[BindProperty]
public string ImageUrl { get; set; }
public string curPath { get; set; }
string webRootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");

string BaiduAI_OCRPath="Uploads//BaiduAIs//";
string BaiduAI_OCRUrl="/BaiduAIs/";
string OCR_API_KEY="你的API KEY";
string OCR_SECRET_KEY="你的SECRET KEY";

public async Task OnPostBusinessLicenseAsync()
{
    if (FileUpload is null)
    {
        ModelState.AddModelError(string.Empty, "请先选择需要识别的图片!");
    }
    if (!ModelState.IsValid)
    {
        return Page();
    }
    msg = new List();

    string fileDir = Path.Combine(webRootPath, BaiduAI_OCRPath);
    string imgName = GetRandomName();

    imgName = await UploadFile(FileUpload, fileDir);

    string fileName = Path.Combine(fileDir, imgName);
    string imgBase64 = GetFileBase64(fileName);
    curPath = Path.Combine(BaiduAI_OCRUrl, imgName);

    DateTime startTime = DateTime.Now;

    string result = GetOCRJson(imgBase64, OCR_API_KEY, OCR_SECRET_KEY);

    DateTime endTime = DateTime.Now;
    TimeSpan ts = endTime - startTime;

    JObject jo = (JObject)JsonStringToObj(result);

    try
    {
        if (jo["error_code"] != null)
        {
            msg.Add("调用失败:" + jo["error_code"].ToString() + "-" + jo["error_msg"].ToString());
        }
        else
        {
            msg.Add("营业执照识别结果(耗时" + ts.TotalSeconds + "秒):\n");
            msg.Add("识别结构数:" + jo["words_result_num"].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());
            msg.Add("有效期:" + jo["words_result"]["有效期"]["words"].ToString());
            msg.Add("类型:" + jo["words_result"]["类型"]["words"].ToString());
        }
    }
    catch (Exception e)
    {
        msg.Add("发生异常:");
        msg.Add(result);
        msg.Add(e.Message);
    }
    return Page();
}

其他相关函数:

/// 
/// 文字识别Json字符串
/// 
/// 图片base64编码
/// API Key
/// Secret Key
/// 
public static string GetOCRJson( string imgbase64, string clientId, string clientSecret)
{
    string token = GetAccessToken(clientId, clientSecret);
    string host = "https://aip.baidubce.com/rest/2.0/ocr/v1/business_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(imgbase64);
    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;
}

/// 
/// 获取百度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;
}

/// 
/// 生成一个随机唯一文件名(Guid)
/// 
/// 
public static string GetRandomName()
{
    return Guid.NewGuid().ToString("N");
}

/// 
/// 返回文件的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转为对象
/// 
/// Json字符串
/// 
public static Object JsonStringToObj(string jsonString)
{
    Object s = JsonConvert.DeserializeObject(jsonString);
    return s;
}

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

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

    return imgName;
}

二、效果测试

1、页面:

2、识别结果:

2.1

2.2

2.3

三、测试结果及建议

从上面的测试结果可以看到,百度营业执照识别技术相当准确,有些图片比较模糊,肉眼观察可能比较费劲,使用百度营业执照识别技术能够更加快速、准确的识别出来。

百度营业执照识别技术对于不通类型样式的营业执照基本上都能准确识别出社会信用代码、经营范围、类型、单位名称、成立日期、有效日期、等关键信息,不过对于注册资本这个字段可能识别的不太准确,比如图2.1和图2.3,对于图2.1,正确识别出来注册资本数字,但是后面加上了“万元”,就错了;对于图2.3,因为注册资本不是数字是大写数字,所以就无法准确识别了,这点还需要改进。

收藏
点赞
0
个赞
TOP
切换版块