接入百度大腦駕駛行爲分析能力,提高規範駕駛提示

一、功能介紹

對於輸入的一張車載監控圖片(可正常解碼,且長寬比適宜),識別圖像中是否有人體(駕駛員),若檢測到至少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種典型行爲姿態。另外,可以根據不同的駕駛場景/要求,設定不同的閾值,從而達到不同的識別要求。

    可以結合【百度語音】技術,採取語音提醒等預警方式,提醒正在駕駛的司機注意自己的不好的駕駛行爲,及時預警,可以有效降低事故發生率,保證生命財產安全。

    可以結合【人體檢測和屬性識別】技術,識別車內的人員數量,根據設定的閾值判斷車輛是否超載,並根據超載嚴重程序進行不同的預警。

    如若能夠識別司機是否疲勞駕駛、是否處於情緒不穩定的狀態,並給出相應的預警提醒就更好了。

    不過,個人覺得,最關鍵的,是需要將危險行駛行爲識別跟交警部門進行數據互通,及時上傳司機的危險駕駛行爲,並根據司機危險形式行爲的嚴重程度,做出相應的懲罰,這樣才能真正有效減少事故發生率,因爲其實司機能夠考取駕駛證,說明他/她心裏是十分清楚自己的行爲是否是危險駕駛行爲,但是抱着僥倖心理,所以纔會做出危險駕駛行爲的,漸漸的讓危險駕駛行爲變成了一種常態,單純的預警實際效果是比較差的。

作者:讓天涯

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章