一、功能介紹
對于輸入的一張車載監控圖片(可正常解碼,且長寬比適宜),識別影像中是否有人體(駕駛員),若檢測到至少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="https://www.cnblogs.com/AIBOOM/p/@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種典型行為姿態,另外,可以根據不同的駕駛場景/要求,設定不同的閾值,從而達到不同的識別要求,
可以結合【百度語音】技術,采取語音提醒等預警方式,提醒正在駕駛的司機注意自己的不好的駕駛行為,及時預警,可以有效降低事故發生率,保證生命財產安全,
可以結合【人體檢測和屬性識別】技術,識別車內的人員數量,根據設定的閾值判斷車輛是否超載,并根據超載嚴重程式進行不同的預警,
如若能夠識別司機是否疲勞駕駛、是否處于情緒不穩定的狀態,并給出相應的預警提醒就更好了,
不過,個人覺得,最關鍵的,是需要將危險行駛行為識別跟交警部門進行資料互通,及時上傳司機的危險駕駛行為,并根據司機危險形式行為的嚴重程度,做出相應的懲罰,這樣才能真正有效減少事故發生率,因為其實司機能夠考取駕駛證,說明他/她心里是十分清楚自己的行為是否是危險駕駛行為,但是抱著僥幸心理,所以才會做出危險駕駛行為的,漸漸的讓危險駕駛行為變成了一種常態,單純的預警實際效果是比較差的,
作者:讓天涯
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/5468.html
標籤:其他
