一、功能介绍

对于输入的一张车载监控图片(可正常解码,且长宽比适宜),识别图像中是否有人体(驾驶员),若检测到至少1个人体,则进一步识别属性行为,可识别使用手机、抽烟、未系安全带、双手离开方向盘、视线未朝前方5种典型行为姿态。

图片质量要求:

1、服务只适用于车载司机场景,请使用驾驶室的真实监控图片测试,勿用网图、非车载场景的普通监控图片、或者乘客的监控图片测试,否则效果不具备代表性。

2、车内摄像头硬件选型无特殊要求,分辨率建议720p以上,但更低分辨率的图片也能识别,只是效果可能有差异。

3、车内摄像头部署方案建议:尽可能拍全驾驶员的身体,并充分考虑背光、角度、方向盘遮挡等因素。

4、服务适用于夜间红外监控图片,识别效果跟可见光图片相比可能略微有差异。

5、图片主体内容清晰可见,模糊、驾驶员遮挡严重、光线暗等情况下,识别效果肯定不理想。

具体功能说明,请参考官方说明文档(驾驶行为分析):https://ai.baidu.com/docs#/Body-API/fd34bf01

二、应用场景

1、营运车辆驾驶监测 
针对出租车、客车、公交车、货车等各类营运车辆,实时监控车内情况,识别驾驶员抽烟、使用手机、未系安全带等危险行为,及时预警,降低事故发生率,保障人身财产安全。
2、社交内容分析审核 
汽车类论坛、社区平台,对配图库以及用户上传的UGC图片进行分析识别,自动过滤出涉及危险驾驶行为的不良图片,有效减少人力成本并降低业务违规风险。

三、使用攻略

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

(1)、登陆 百度智能云-管理中心 创建 “人体分析”应用,获取 “API Key ”和 “Secret Key”:https://console.bce.baidu.com/ai/?_=1566223151105&fromai=1#/ai/body/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="DriverBehavior" ,提交并返回识别结果。

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

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

2.2 后台代码

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

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


        public async Task OnPostDriverBehaviorAsync()
        {
            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 = GetFileBase64(fileName);
            curPath = Path.Combine("/BaiduAIs/", imgName);//需在Startup.cs 文件 的 Configure(IApplicationBuilder app, IHostingEnvironment env)方法中开启虚拟目录映射功能


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

            List msgList = jo["person_info"].ToList();
            int number = int.Parse(jo["person_num"].ToString());
            int curNumber = 1;
            float score = 0;
            float threshold = 0;
            msg.Add("人数:" + number + "");
            foreach (JToken ms in msgList)
            {
                if (number > 1)
                {
                    msg.Add("第 " + (curNumber++).ToString() + " 人:");
                }
                score = float.Parse(ms["attributes"]["smoke"]["score"].ToString());
                threshold = float.Parse(ms["attributes"]["smoke"]["threshold"].ToString());
                msg.Add("吸烟:" + (score > threshold ? "大概率" : "小概率"));
                msg.Add("概率:" + score.ToString());
                msg.Add("阈值:" + threshold.ToString());

                score = float.Parse(ms["attributes"]["cellphone"]["score"].ToString());
                threshold = float.Parse(ms["attributes"]["cellphone"]["threshold"].ToString());
                msg.Add("使用手机:" + (score > threshold ? "大概率" : "小概率"));
                msg.Add("概率:" + score.ToString());
                msg.Add("阈值:" + threshold.ToString());

                score = float.Parse(ms["attributes"]["not_buckling_up"]["score"].ToString());
                threshold = float.Parse(ms["attributes"]["not_buckling_up"]["threshold"].ToString());
                msg.Add("未系安全带:" + (score > threshold ? "大概率" : "小概率"));
                msg.Add("概率:" + score.ToString());
                msg.Add("阈值:" + threshold.ToString());

                score = float.Parse(ms["attributes"]["both_hands_leaving_wheel"]["score"].ToString());
                threshold = float.Parse(ms["attributes"]["both_hands_leaving_wheel"]["threshold"].ToString());
                msg.Add("双手离开方向盘:" + (score > threshold ? "大概率" : "小概率"));
                msg.Add("概率:" + score.ToString());
                msg.Add("阈值:" + threshold.ToString());

                score = float.Parse(ms["attributes"]["not_facing_front"]["score"].ToString());
                threshold = float.Parse(ms["attributes"]["not_facing_front"]["threshold"].ToString());
                msg.Add("视角未朝前方:" + (score > threshold ? "大概率" : "小概率"));
                msg.Add("概率:" + score.ToString());
                msg.Add("阈值:" + threshold.ToString());
            }
            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 GetBodyeJson(string strbaser64, string clientId, string clientSecret)
        {
            string token = GetAccessToken(clientId, clientSecret);
            string host = "https://aip.baidubce.com/rest/2.0/image-classify/v1/driver_behavior?access_token=" + token;
            Encoding encoding = Encoding.Default;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
            request.Method = "post";
            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

2.4

2.5

四、测试结果及建议

    从上图中测试结果可知,百度的驾驶行为分析整体识别效果还是不错的,可以比较准确的识别使用手机、抽烟、未系安全带、双手离开方向盘、视线未朝前方5种典型行为姿态。另外,可以根据不同的驾驶场景/要求,设定不同的阈值,从而达到不同的识别要求。

    可以结合【百度语音】技术,采取语音提醒等预警方式,提醒正在驾驶的司机注意自己的不好的驾驶行为,及时预警,可以有效降低事故发生率,保证生命财产安全。

    可以结合【人体检测和属性识别】技术,识别车内的人员数量,根据设定的阈值判断车辆是否超载,并根据超载严重程序进行不同的预警。

    如若能够识别司机是否疲劳驾驶、是否处于情绪不稳定的状态,并给出相应的预警提醒就更好了。

    不过,个人觉得,最关键的,是需要将危险行驶行为识别跟交警部门进行数据互通,及时上传司机的危险驾驶行为,并根据司机危险形式行为的严重程度,做出相应的惩罚,这样才能真正有效减少事故发生率,因为其实司机能够考取驾驶证,说明他/她心里是十分清楚自己的行为是否是危险驾驶行为,但是抱着侥幸心理,所以才会做出危险驾驶行为的,渐渐的让危险驾驶行为变成了一种常态,单纯的预警实际效果是比较差的。

作者:让天涯

posted on 2019-11-19 20:19  AIBOOM  阅读(410)  评论(0编辑  收藏  举报