C#使用旷视接口实现人脸识别 – NA博客

C#使用旷视接口实现人脸识别

人脸识别在现在的应用开发中使用频率越来越高,最近公司某应用要把用户上传的人像与身份证进行对比,使用到了旷视的API,下面把通用类和调用代码贴上来,希望能帮到需要实现这种功能的童鞋。

基础类:

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
 
namespace FaceDemo.Models
{
    public static class HttpHelper4MultipartForm
    {
        public class FileParameter
        {
            public byte[] File
            {
                get;
                set;
            }

            public string FileName
            {
                get;
                set;
            }

            public string ContentType
            {
                get;
                set;
            }

            public FileParameter(byte[] file) : this(file, null)
            {
            }

            public FileParameter(byte[] file, string filename) : this(file, filename, null)
            {
            }

            public FileParameter(byte[] file, string filename, string contenttype)
            {
                this.File = file;
                this.FileName = filename;
                this.ContentType = contenttype;
            }
        }

        private static readonly Encoding encoding = Encoding.UTF8;
        /// <summary>
        /// MultipartForm请求
        /// </summary>
        /// <param name="postUrl">服务地址</param>
        /// <param name="userAgent"></param>
        /// <param name="postParameters">参数</param>
        /// <returns></returns>
        public static HttpWebResponse MultipartFormDataPost(string postUrl, string userAgent, Dictionary<string, object> postParameters)
        {
            string text = string.Format("----------{0:N}", Guid.NewGuid());
            string contentType = "multipart/form-data; boundary=" + text;//multipart类型
            byte[] multipartFormData = HttpHelper4MultipartForm.GetMultipartFormData(postParameters, text);
            return HttpHelper4MultipartForm.PostForm(postUrl, userAgent, contentType, multipartFormData);
        }

        private static HttpWebResponse PostForm(string postUrl, string userAgent, string contentType, byte[] formData)
        {
            HttpWebRequest httpWebRequest = WebRequest.Create(postUrl) as HttpWebRequest;
            if (httpWebRequest == null)
            {
                throw new NullReferenceException("request is not a http request");
            }

            httpWebRequest.Method = "POST";//post方式
            httpWebRequest.SendChunked = false;
            httpWebRequest.KeepAlive = true;
            httpWebRequest.Proxy = null;
            httpWebRequest.Timeout = Timeout.Infinite;
            httpWebRequest.ReadWriteTimeout = Timeout.Infinite;
            httpWebRequest.AllowWriteStreamBuffering = false;
            httpWebRequest.ProtocolVersion = HttpVersion.Version11;
            httpWebRequest.ContentType = contentType;
            httpWebRequest.CookieContainer = new CookieContainer();
            httpWebRequest.ContentLength = (long)formData.Length;

            try
            {
                using (Stream requestStream = httpWebRequest.GetRequestStream())
                {
                    int bufferSize = 4096;
                    int position = 0;
                    while (position < formData.Length)
                    {
                        bufferSize = Math.Min(bufferSize, formData.Length - position);
                        byte[] data = new byte[bufferSize];
                        Array.Copy(formData, position, data, 0, bufferSize);
                        requestStream.Write(data, 0, data.Length);
                        position += data.Length;
                    }
                    requestStream.Close();
                }
            }
            catch (Exception ex)
            {
                return null;
            }

            HttpWebResponse result;
            try
            {
                result = (httpWebRequest.GetResponse() as HttpWebResponse);
            }
            catch (WebException arg_9C_0)
            {
                result = (arg_9C_0.Response as HttpWebResponse);
            }
            return result;
        }

        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }

        /// <summary>
        /// 从表单中获取数据
        /// </summary>
        /// <param name="postParameters"></param>
        /// <param name="boundary"></param>
        /// <returns></returns>
        private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)
        {
            Stream stream = new MemoryStream();
            bool flag = false;
            foreach (KeyValuePair<string, object> current in postParameters)
            {
                if (flag)
                {
                    stream.Write(HttpHelper4MultipartForm.encoding.GetBytes("\r\n"), 0, HttpHelper4MultipartForm.encoding.GetByteCount("\r\n"));
                }
                flag = true;
                if (current.Value is HttpHelper4MultipartForm.FileParameter)
                {
                    HttpHelper4MultipartForm.FileParameter fileParameter = (HttpHelper4MultipartForm.FileParameter)current.Value;
                    string s = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n", new object[]
                    {
                        boundary,
                        current.Key,
                        fileParameter.FileName ?? current.Key,
                        fileParameter.ContentType ?? "application/octet-stream"
                    });
                    stream.Write(HttpHelper4MultipartForm.encoding.GetBytes(s), 0, HttpHelper4MultipartForm.encoding.GetByteCount(s));
                    stream.Write(fileParameter.File, 0, fileParameter.File.Length);
                }
                else
                {
                    string s2 = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}", boundary, current.Key, current.Value);
                    stream.Write(HttpHelper4MultipartForm.encoding.GetBytes(s2), 0, HttpHelper4MultipartForm.encoding.GetByteCount(s2));
                }
            }
            string s3 = "\r\n--" + boundary + "--\r\n";
            stream.Write(HttpHelper4MultipartForm.encoding.GetBytes(s3), 0, HttpHelper4MultipartForm.encoding.GetByteCount(s3));
            stream.Position = 0L;
            byte[] array = new byte[stream.Length];
            stream.Read(array, 0, array.Length);
            stream.Close();
            return array;
        }
    }
}

调用类:

using FaceDemo.Models;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace FaceDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            string returnst= GetImage();
            return View();

        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        public string GetImage()
        {

            Dictionary<string, object> verifyPostParameters = new Dictionary<string, object>();
            verifyPostParameters.Add("api_key", "替换");
            verifyPostParameters.Add("api_secret", "替换");
            verifyPostParameters.Add("comparison_type", "1");
            verifyPostParameters.Add("face_image_type", "raw_image");
            verifyPostParameters.Add("idcard_name", "姓名");
            verifyPostParameters.Add("idcard_number", "身份证号");

            Bitmap bmp = new Bitmap(@"D:/renlianshibie.jpg"); // 图片地址
            byte[] fileImage;
            using (Stream stream1 = new MemoryStream())
            {
                bmp.Save(stream1, ImageFormat.Jpeg);
                byte[] arr = new byte[stream1.Length];
                stream1.Position = 0;
                stream1.Read(arr, 0, (int)stream1.Length);
                stream1.Close();
                fileImage = arr;
            }

            //添加图片参数
            verifyPostParameters.Add("image", new HttpHelper4MultipartForm.FileParameter(fileImage, "renlianshibie.jpg", "application/octet-stream"));

            HttpWebResponse verifyResponse = HttpHelper4MultipartForm.MultipartFormDataPost("https://api.megvii.com/faceid/v2/verify", "", verifyPostParameters);

            StreamReader myStreamReader = new StreamReader(verifyResponse.GetResponseStream(), Encoding.UTF8);

            return myStreamReader.ReadToEnd();

        }
    }
}

效果图:

清风

心中有梦想就要一如既往,不能遇到困难说放就放,千锤百炼才能磨炼出好钢,饱经风霜才能更强。

相关推荐

发表评论

电子邮件地址不会被公开。 必填项已用*标注



微信扫一扫,分享到朋友圈

C#使用旷视接口实现人脸识别
返回顶部

显示

忘记密码?

显示

显示

获取验证码

Close