目录
[Craneoffice.net 采用的识别方式](#Craneoffice.net 采用的识别方式)
腾讯云人脸核身技术
根据腾讯云的官方介绍,其慧眼人脸核身是一组对用户身份信息真实性进行验证审核的服务套件,提供人脸核身、身份信息核验、银行卡要素核验和运营商类要素核验等各类实名信息认证能力,以解决行业内大量对用户身份信息核实的需求。
Craneoffice.net 采用的识别方式
由于其产品众多,考虑一些综合因素,我们在 Craneoffice.net 架构里主要实现以下三种识别方式:
1、活体人脸核身(权威库):
流程为通过录制一段人脸活体静态视频,与大数据权威库身份证信息进行比对,判断是否为 同一人。
2、活体人脸比对:
流程为通过上传正确、清晰的身份证正面图片,截取头像图片,再通过录制人脸活体静态视频进行比对,判断是否为同一人。
3、照片人脸核身(权威库):
流程为上传正确的身份证正面图片,截取头像图片,传递身份证号与姓名,与大数据权威库身份证信息进行比对,判断是否为同一人。
调用成本
申请开发账号及具体费用情况请访问腾讯云人脸核身产品首页:
https://cloud.tencent.com/act/pro/huiyandiscount
我们的产品调用成本如下表,可参照一下比例,在此仅供参考:
|-------------|-------------|
| 识别方式 | 调用成功的成本 |
| 活体人脸核身(权威库) | 1元 / 每次 |
| 活体人脸比对 | 0.15元 / 每次 |
| 照片人脸核身(权威库) | 1元 / 每次 |
总之,在腾讯云商城购买越大的产品包调用成本越低,如果有优惠活动则更为合适。
百度云身份证识别
其官方宣传可以结构化识别二代居民身份证正反面所有8个字段,识别准确率超过99%;支持识别混贴身份证,适用于同一张图上有多张身份证正反面的场景;支持检测身份证正面头像,并返回头像切片的base64编码及位置信息,其具体详细产品介绍请访问如下地址:
https://ai.baidu.com/tech/ocr_cards/idcard
调用成本
我们使用的是企业申请,一个月应该可以享受2000次免费调用,后期调用应该是0.02元左右每次,具体可参照:
https://ai.baidu.com/ai-doc/OCR/fk3h7xune#%E8%BA%AB%E4%BB%BD%E8%AF%81%E8%AF%86%E5%88%AB
相关结合点
在人脸核身方面,虽然我们可以直接提供身份证号、姓名、自拍抠图的头像BASE64编码等参数传递给腾讯云识别接口,但考虑到实际应用场景中,更加规范、有效的验证有助于提升应用程序数据的质量和精准性,也更加保障了识别结果的准确性。
因此身份证的识别功能和人脸核身功能即可以单独独立运行,又可以利用产品特性相结合,实现数据采集、校验的双保险。
具体流程如下图:
核心代码
实现调用人脸核身API的示例
该示例代码以上小节的介绍的三种识别方式实现,仅供参考:
cs
//定义人脸识别类
public class FaceR
{
public string ResultJson = ""; //记录返回 json 结果
public string apiurl = "faceid.tencentcloudapi.com"; //腾讯人脸识别API地址
public string debuginfo = ""; //调试信息
public string ErrorMessage = ""; //错误信息
string[] signHeaders = null; //头部签名数组
public FaceR()
{
}
//活体人脸核身方法,参数为身份证号;检验类型,这里传固定值 SILENT;姓名;活体的静态视频编码;方法返回相似度值等信息
public string LivenessRecognition(string IdCard,string LivenessType,string Name,string VideoBase64)
{
string content = "{ \"IdCard\":\"" + IdCard + "\",\"LivenessType\":\"" + LivenessType + "\", \"Name\":\"" + Name + "\" ,\"VideoBase64\":\"" + VideoBase64 + "\"}";
// 密钥参数
string SECRET_ID = 你申请的ID
string SECRET_KEY = 你申请的KEY
string service = "faceid";
string endpoint = "faceid.tencentcloudapi.com";
string region = "ap-guangzhou";
string action = "LivenessRecognition";
string version = "2018-03-01";
// 注意时区,建议此时间统一采用UTC时间戳,否则容易出错
DateTime date = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(1551113065);
date = DateTime.UtcNow;
string requestPayload = content;
Dictionary<string, string> headers = BuildHeaders(SECRET_ID, SECRET_KEY, service
, endpoint, region, action, version, date, requestPayload);
string rv = "POST https://faceid.tencentcloudapi.com\n";
ArrayList hs = new ArrayList();
foreach (KeyValuePair<string, string> kv in headers)
{
rv += (kv.Key + ": " + kv.Value) + "\n";
hs.Add(kv.Key + ": " + kv.Value);
}
rv += "\n";
hs.Add("");
rv += requestPayload + "\n";
string[] hss = new string[hs.Count];
debuginfo = "";
for (int i = 0; i < hs.Count; i++)
{
hss[i] = hs[i].ToString();
debuginfo += hss[i] + "\r\n";
}
signHeaders = hss;
string rvs = "";
rvs=GetResponseResult("https://faceid.tencentcloudapi.com", Encoding.UTF8, "POST",content, signHeaders);
return rvs;
}
//活体人脸比对方法,参数为传递检验类型,这里传固定值 SILEN;身份证头像图片编码;活体的静态视频编码,方法返回相似度值等信息
public string LivenessCompare(string LivenessType, string ImageBase64, string VideoBase64)
{
string content = "{ \"LivenessType\":\"" + LivenessType + "\", \"ImageBase64\":\"" + ImageBase64 + "\" ,\"VideoBase64\":\"" + VideoBase64 + "\"}";
// 密钥参数
string SECRET_ID = 你申请的ID
string SECRET_KEY = 你申请的KEY
string service = "faceid";
string endpoint = "faceid.tencentcloudapi.com";
string region = "ap-guangzhou";
string action = "LivenessCompare";
string version = "2018-03-01";
// 注意时区,建议此时间统一采用UTC时间戳,否则容易出错
DateTime date = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(1551113065);
date = DateTime.UtcNow;
string requestPayload = content;
Dictionary<string, string> headers = BuildHeaders(SECRET_ID, SECRET_KEY, service
, endpoint, region, action, version, date, requestPayload);
string rv = "POST https://faceid.tencentcloudapi.com\n";
ArrayList hs = new ArrayList();
foreach (KeyValuePair<string, string> kv in headers)
{
rv += (kv.Key + ": " + kv.Value) + "\n";
hs.Add(kv.Key + ": " + kv.Value);
}
rv += "\n";
hs.Add("");
rv += requestPayload + "\n";
string[] hss = new string[hs.Count];
debuginfo = "";
for (int i = 0; i < hs.Count; i++)
{
hss[i] = hs[i].ToString();
debuginfo += hss[i] + "\r\n";
}
signHeaders = hss;
string rvs = "";
rvs = GetResponseResult("https://faceid.tencentcloudapi.com", Encoding.UTF8, "POST", content, signHeaders);
return rvs;
}
//照片人脸核身方法,参数传递身份证号;姓名;截取的身份证头像图片编码;方法返回相似度值等信息
public string ImageRecognition(string IdCard,string Name, string ImageBase64)
{
string content = "{ \"IdCard\":\"" + IdCard + "\", \"Name\":\"" + HttpUtility.UrlDecode(Name, Encoding.UTF8) + "\" ,\"ImageBase64\":\"" + ImageBase64 + "\"}";
// 密钥参数
string SECRET_ID = 你申请的ID
string SECRET_KEY = 你申请的KEY
string service = "faceid";
string endpoint = "faceid.tencentcloudapi.com";
string region = "ap-guangzhou";
string action = "ImageRecognition";
string version = "2018-03-01";
// 注意时区,建议此时间统一采用UTC时间戳,否则容易出错
DateTime date = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(1551113065);
date = DateTime.UtcNow;
string requestPayload = content;
Dictionary<string, string> headers = BuildHeaders(SECRET_ID, SECRET_KEY, service
, endpoint, region, action, version, date, requestPayload);
string rv = "POST https://faceid.tencentcloudapi.com\n";
ArrayList hs = new ArrayList();
foreach (KeyValuePair<string, string> kv in headers)
{
rv += (kv.Key + ": " + kv.Value) + "\n";
hs.Add(kv.Key + ": " + kv.Value);
}
rv += "\n";
hs.Add("");
rv += requestPayload + "\n";
string[] hss = new string[hs.Count];
debuginfo = "";
for (int i = 0; i < hs.Count; i++)
{
hss[i] = hs[i].ToString();
debuginfo += hss[i] + "\r\n";
}
signHeaders = hss;
string rvs = "";
rvs = GetResponseResult("https://faceid.tencentcloudapi.com", Encoding.UTF8, "POST", content, signHeaders);
return rvs;
}
//SHA256Hex算法
public static string SHA256Hex(string s)
{
using (SHA256 algo = SHA256.Create())
{
byte[] hashbytes = algo.ComputeHash(Encoding.UTF8.GetBytes(s));
StringBuilder builder = new StringBuilder();
for (int i = 0; i < hashbytes.Length; ++i)
{
builder.Append(hashbytes[i].ToString("x2"));
}
return builder.ToString();
}
}
//HMAC-SHA256算法
public static byte[] HmacSHA256(byte[] key, byte[] msg)
{
using (HMACSHA256 mac = new HMACSHA256(key))
{
return mac.ComputeHash(msg);
}
}
//构造头部签名
public static Dictionary<String, String> BuildHeaders(string secretid,
string secretkey, string service, string endpoint, string region,
string action, string version, DateTime date, string requestPayload)
{
string datestr = date.ToString("yyyy-MM-dd");
DateTime startTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
long requestTimestamp = (long)Math.Round((date - startTime).TotalMilliseconds, MidpointRounding.AwayFromZero) / 1000;
// ************* 步骤 1:拼接规范请求串 *************
string algorithm = "TC3-HMAC-SHA256";
string httpRequestMethod = "POST";
string canonicalUri = "/";
string canonicalQueryString = "";
string contentType = "application/json";
string canonicalHeaders = "content-type:" + contentType + "; charset=utf-8\n"
+ "host:" + endpoint + "\n"
+ "x-tc-action:" + action.ToLower() + "\n";
string signedHeaders = "content-type;host;x-tc-action";
string hashedRequestPayload = SHA256Hex(requestPayload);
string canonicalRequest = httpRequestMethod + "\n"
+ canonicalUri + "\n"
+ canonicalQueryString + "\n"
+ canonicalHeaders + "\n"
+ signedHeaders + "\n"
+ hashedRequestPayload;
Console.WriteLine(canonicalRequest);
// ************* 步骤 2:拼接待签名字符串 *************
string credentialScope = datestr + "/" + service + "/" + "tc3_request";
string hashedCanonicalRequest = SHA256Hex(canonicalRequest);
string stringToSign = algorithm + "\n"
+ requestTimestamp.ToString() + "\n"
+ credentialScope + "\n"
+ hashedCanonicalRequest;
Console.WriteLine(stringToSign);
// ************* 步骤 3:计算签名 *************
byte[] tc3SecretKey = Encoding.UTF8.GetBytes("TC3" + secretkey);
byte[] secretDate = HmacSHA256(tc3SecretKey, Encoding.UTF8.GetBytes(datestr));
byte[] secretService = HmacSHA256(secretDate, Encoding.UTF8.GetBytes(service));
byte[] secretSigning = HmacSHA256(secretService, Encoding.UTF8.GetBytes("tc3_request"));
byte[] signatureBytes = HmacSHA256(secretSigning, Encoding.UTF8.GetBytes(stringToSign));
string signature = BitConverter.ToString(signatureBytes).Replace("-", "").ToLower();
Console.WriteLine(signature);
// ************* 步骤 4:拼接 Authorization *************
string authorization = algorithm + " "
+ "Credential=" + secretid + "/" + credentialScope + ", "
+ "SignedHeaders=" + signedHeaders + ", "
+ "Signature=" + signature;
Console.WriteLine(authorization);
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("Authorization", authorization);
headers.Add("Host", endpoint);
headers.Add("Content-Type", contentType + "; charset=utf-8");
headers.Add("X-TC-Timestamp", requestTimestamp.ToString());
headers.Add("X-TC-Version", version);
headers.Add("X-TC-Action", action);
headers.Add("X-TC-Region", region);
return headers;
}
//调用API地址,传递参数并获取返回值的通用方法
public string GetResponseResult(string url, System.Text.Encoding encoding, string method, string postData, string[] headers, string ContentType = "application/x-www-form-urlencoded")
{
method = method.ToUpper();
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;
if (method == "GET")
{
try
{
WebRequest request2 = WebRequest.Create(@url);
request2.Method = method;
WebResponse response2 = request2.GetResponse();
Stream stream = response2.GetResponseStream();
StreamReader reader = new StreamReader(stream, encoding);
string content = reader.ReadToEnd();
return content;
}
catch (Exception ex)
{
ErrorMessage = ex.Message;
return "";
}
}
Stream outstream = null;
Stream instream = null;
StreamReader sr = null;
HttpWebResponse response = null;
HttpWebRequest request = null;
byte[] data = encoding.GetBytes(postData);
// 准备请求...
try
{
// 设置参数
request = WebRequest.Create(url) as HttpWebRequest;
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
request.Method = method;
debuginfo = headers.GetLength(0).ToString()+"\r\n";
if (headers != null)
{
for (int i = 0; i < headers.GetLength(0); i++)
{
if (headers[i].Split(':').Length < 2)
{
continue;
}
debuginfo += i.ToString()+headers[i]+"\r\n";
if (headers[i].Split(':').Length > 1)
{
if (headers[i].Split(':')[0] == "Host")
{
request.Host = headers[i].Split(':')[1].Trim();
continue;
}
else if (headers[i].Split(':')[0] == "Content-Type")
{
request.ContentType = headers[i].Split(':')[1].Trim();
ContentType = headers[i].Split(':')[1].Trim();
continue;
}
}
request.Headers.Add(headers[i].Trim());
}
debuginfo += "sd2" + "\r\n";
}
request.ContentType = ContentType;
request.ContentLength = data.Length;
outstream = request.GetRequestStream();
outstream.Write(data, 0, data.Length);
outstream.Close();
//发送请求并获取相应回应数据
response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
instream = response.GetResponseStream();
sr = new StreamReader(instream, encoding);
//返回结果网页(html)代码
string content = sr.ReadToEnd();
return content;
}
catch (Exception ex)
{
ErrorMessage = ex.Message;
return "";
}
}//get response result
}
实现调用身份证识别API的示例
cs
public class IdCard
{
public string name = ""; //姓名
public string sex = ""; //性别
public string photo_base64 = ""; //截取的身份证头像图像的编码值
public string nation = ""; //民族
public string address = ""; //住址
public string IDNumber = ""; //身份证号
public string birthday = ""; //生日
public string org = ""; //发证机关
public string startDate = ""; //有效期起
public string endDate = ""; //有效期止
public string ResultJson = ""; //记录返回的JSON值
public string ErrorMessage = ""; //记录错误信息
public string direction = ""; //上传时图片的方向
public string image_status = ""; //上传图片的识别状态
public string risk_type = ""; //上传图片的识别类型
public string edit_tool = ""; //上传图片是否P图
public string idcard_number_type = ""; //上传图片的识别错误信息
public IdCard()
{
}
//得到指定文件的 byte[],参数为文件绝对路径值
private byte[] getImageByte(string imagePath)
{
FileStream files = new FileStream(imagePath, FileMode.Open);
byte[] imgByte = new byte[files.Length];
files.Read(imgByte, 0, imgByte.Length);
files.Close();
return imgByte;
}
//识别身份证信息方法,参数为文件绝对路径值;正反面值:正面传 front,反面传 back
public void valid(string imagePath, string id_card_side)
{
name = "";
sex = "";
photo_base64 = "";
nation = "";
address = "";
IDNumber = "";
birthday = "";
org = "";
startDate = "";
endDate = "";
direction="";
image_status = "";
risk_type = "";
edit_tool = "";
idcard_number_type = "";
byte[] image = getImageByte(imagePath);
var APP_ID = 申请的开发ID;
var API_KEY = 申请的开发KEY;
var SECRET_KEY = 开发密钥;
var client = new Baidu.Aip.Ocr.Ocr(API_KEY, SECRET_KEY);
client.Timeout = 60000; // 修改超时时间
Newtonsoft.Json.Linq.JObject result = new JObject();
var options = new Dictionary<string, object>{
{"detect_risk", "true"},
{"detect_direction", "true"},
{"detect_photo", "true"}
};
try
{
result = client.Idcard(image, id_card_side, options);
ResultJson = result.ToString();
if (id_card_side == "front")
{
name = result["words_result"]["姓名"]["words"].ToString();
sex = result["words_result"]["性别"]["words"].ToString();
nation = result["words_result"]["民族"]["words"].ToString();
address = result["words_result"]["住址"]["words"].ToString();
IDNumber = result["words_result"]["公民身份号码"]["words"].ToString();
photo_base64 = result["photo"].ToString();
birthday = result["words_result"]["出生"]["words"].ToString();
birthday = birthday.Substring(0, 4) + "-" + birthday.Substring(4, 2) + "-" + birthday.Substring(6, 2);
}
if (id_card_side == "back")
{
org = result["words_result"]["签发机关"]["words"].ToString();
startDate = result["words_result"]["签发日期"]["words"].ToString();
startDate = startDate.Substring(0, 4) + "-" + startDate.Substring(4, 2) + "-" + startDate.Substring(6, 2);
endDate = result["words_result"]["失效日期"]["words"].ToString();
endDate = endDate.Substring(0, 4) + "-" + endDate.Substring(4, 2) + "-" + endDate.Substring(6, 2);
}
direction = result["direction"].ToString();
switch (direction)
{
case "-1":
direction = "未定义";
break;
case "0":
direction = "正向";
break;
case "1":
direction = "逆时针90度";
break;
case "2":
direction = "逆时针180度";
break;
case "3":
direction = "逆时针270度";
break;
}
image_status = result["image_status"].ToString();
switch (image_status)
{
case "normal":
image_status = "识别正常";
break;
case "reversed_side":
image_status = "身份证正反面颠倒";
break;
case "non_idcard":
image_status = "上传的图片中不包含身份证";
break;
case "blurred":
image_status = "身份证模糊";
break;
case "other_type_card":
image_status = "其他类型证照";
break;
case "over_exposure":
image_status = "身份证关键字段反光或过曝";
break;
case "over_dark":
image_status = "身份证欠曝(亮度过低)";
break;
case "unknown":
image_status = "未知状态";
break;
}
risk_type = result["risk_type"].ToString();
switch (risk_type)
{
case "normal":
risk_type = "正常身份证";
break;
case "copy":
risk_type = "复印件";
break;
case "temporary":
risk_type = "临时身份证";
break;
case "screen":
risk_type = "翻拍";
break;
case "unknown":
risk_type = "其他未知情况";
break;
}
if (ResultJson.IndexOf("edit_tool") != -1)
{
edit_tool = result["edit_tool"].ToString();
}
else
{
edit_tool = "未P图";
}
if (ResultJson.IndexOf("idcard_number_type") != -1)
{
idcard_number_type = result["idcard_number_type"].ToString();
switch (idcard_number_type)
{
case "-1":
idcard_number_type = "身份证正面所有字段全为空";
break;
case "0":
idcard_number_type = "身份证证号识别错误";
break;
case "1":
idcard_number_type = "身份证证号和性别、出生信息一致";
break;
case "2":
idcard_number_type = "身份证证号和性别、出生信息都不一致";
break;
case "3":
idcard_number_type = "身份证证号和出生信息不一致";
break;
case "4":
idcard_number_type = "身份证证号和性别信息不一致";
break;
}
}
}
catch (Exception e)
{
ErrorMessage = e.Message;
}
}
}// idcard
小结
采用哪种识别方式,要根据我们在实际的应用场景中进行选择,而且也需要考虑调用的成本(本文涉及的调用成本仅供参考)。这里讲述的几种方案是我们自研产品中所采用的方式,腾讯云的人脸核身产品分支很多,大家可以根据具体需求进行选择、扩充自己的产品功能。
再次感谢您的阅读,欢迎大家讨论指正。