一、功能介紹
對於輸入的一張圖片(可正常解碼,且長寬比適宜),檢測圖像中的所有人體並返回每個人體的矩形框位置,識別人體的靜態屬性和行爲,共支持20餘種屬性,包括:性別、年齡階段、衣着(含類別/顏色)、是否戴帽子、是否戴眼鏡、是否揹包、是否使用手機、身體朝向等。
主要適用於監控場景的中低空斜拍視角,支持人體輕度重疊、輕度遮擋、背面、側面、動作變化等複雜場景。
攝像頭硬件選型無特殊要求,分辨率建議720p以上,更低分辨率的圖片也能識別,只是效果可能有差異。暫不適用夜間紅外監控圖片,後續會考慮擴展。
二、應用場景
1、安防監控
識別人體的性別年齡、衣着外觀等特徵,輔助定位追蹤特定人員;監測預警各類危險、違規行爲(如公共場所跑跳、抽菸),減少安全隱。
2、智能零售
商場、門店等線下零售場景,識別入店及路過客羣的屬性信息,收集消費者畫像,輔助精準營銷、個性化推薦、門店選址、流行趨勢分析等應用。
3、線下廣告投放
樓宇、戶外等廣告屏智能化升級,採集人體信息,分析人羣屬性,定向投放廣告物料,提升用戶體驗和商業效率。
三、使用攻略
說明:本文采用C# 語言,開發環境爲.Net Core 2.1,採用在線API接口方式實現。
(1)、登陸 百度智能雲-管理中心 創建 “人體分析”應用,獲取 “API Key ”和 “Secret Key” :https://console.bce.baidu.com/ai/?_=1561441540695&fromai=1#/ai/body/overview/index
(2)、根據 API Key 和 Secret Key 獲取 AccessToken。
/// <summary>
/// 獲取百度access_token
/// </summary>
/// <param name="clientId">API Key</param>
/// <param name="clientSecret">Secret Key</param>
/// <returns></returns>
public static string GetAccessToken(string clientId, string clientSecret)
{
string authHost = "https://aip.baidubce.com/oauth/2.0/token";
HttpClient client = new HttpClient();
List<KeyValuePair<string, string>> paraList = new List<KeyValuePair<string, string>>();
paraList.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
paraList.Add(new KeyValuePair<string, string>("client_id", clientId));
paraList.Add(new KeyValuePair<string, string>("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="BodyAttr" ,提交併返回識別結果。
一個img:src="@Model.curPath",顯示識別的圖片。
最後顯示後臺 msg 字符串列表信息。
2.2 後臺代碼:
[BindProperty]
public IFormFile FileUpload { get; set; }
private readonly IHostingEnvironment HostingEnvironment;
public List<string> msg = new List<string>();
public string curPath { get; set; }
public BodySearchModel(IHostingEnvironment hostingEnvironment)
{
HostingEnvironment = hostingEnvironment;
}
public async Task<IActionResult> OnPostBodyAttrAsync()
{
if (FileUpload is null)
{
ModelState.AddModelError(string.Empty, "請先選擇本地圖片!");
}
if (!ModelState.IsValid)
{
return Page();
}
msg = new List<string>();
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<JToken> msgList = jo["person_info"].ToList();
int number = int.Parse(jo["person_num"].ToString());
int curNumber = 1;
msg.Add("人數:" + number);
foreach (JToken ms in msgList)
{
if (number > 1)
{
msg.Add("第 " + (curNumber++).ToString() + " 人:");
}
msg.Add("性別:" + ms["attributes"]["gender"]["name"].ToString());
msg.Add("年齡:" + ms["attributes"]["age"]["name"].ToString());
msg.Add("身體朝向:" + ms["attributes"]["orientation"]["name"].ToString());
msg.Add("下半身服飾:" + ms["attributes"]["lower_wear"]["name"].ToString());
msg.Add("下半身衣着顏色:" + ms["attributes"]["lower_color"]["name"].ToString());
msg.Add("上半身服飾:" + ms["attributes"]["lower_wear"]["name"].ToString());
msg.Add("上半身衣着顏色:" + ms["attributes"]["upper_color"]["name"].ToString());
msg.Add("上身服飾分類:" + ms["attributes"]["upper_wear"]["name"].ToString());
msg.Add("上身服飾紋理:" + ms["attributes"]["upper_wear_texture"]["name"].ToString());
msg.Add("是否戴眼鏡:" + ms["attributes"]["glasses"]["name"].ToString());
msg.Add("是否戴帽子:" + ms["attributes"]["headwear"]["name"].ToString());
msg.Add("是否吸菸:" + ms["attributes"]["smoke"]["name"].ToString());
msg.Add("交通工具:" + ms["attributes"]["vehicle"]["name"].ToString());
msg.Add("使用手機:" + ms["attributes"]["cellphone"]["name"].ToString());
msg.Add("是否撐傘:" + ms["attributes"]["umbrella"]["name"].ToString());
msg.Add("揹包:" + ms["attributes"]["bag"]["name"].ToString());
}
return Page();
}
/// <summary>
/// 上傳文件,返回文件名
/// </summary>
/// <param name="formFile">文件上傳控件</param>
/// <param name="fileDir">文件絕對路徑</param>
/// <returns></returns>
public static async Task<string> 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;
}
/// <summary>
/// 返回圖片的base64編碼
/// </summary>
/// <param name="fileName">文件絕對路徑名稱</param>
/// <returns></returns>
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;
}
/// <summary>
/// 人體檢測Json字符串
/// </summary>
/// <param name="strbaser64">圖片base64編碼</param>
/// <param name="clientId">API Key</param>
/// <param name="clientSecret">Secret Key</param>
/// <returns></returns>
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/body_attr?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
第 1 人:
性別:女性
年齡:青年
身體朝向:正面
下半身服飾:長裙
下半身衣着顏色:藍
上半身服飾:長裙
上半身衣着顏色:白
上身服飾分類:短袖
上身服飾紋理:純色
是否戴眼鏡:戴眼鏡
是否戴帽子:無帽
是否吸菸:未吸菸
交通工具:無交通工具
使用手機:未使用手機
是否撐傘:未打傘
揹包:無揹包
第 2 人:
性別:女性
年齡:青年
身體朝向:正面
下半身服飾:不確定
下半身衣着顏色:不確定
上半身服飾:不確定
上半身衣着顏色:黑
上身服飾分類:短袖
上身服飾紋理:純色
是否戴眼鏡:無眼鏡
是否戴帽子:無帽
是否吸菸:未吸菸
交通工具:無交通工具
使用手機:未使用手機
是否撐傘:未打傘
揹包:無揹包
2.2
完整識別結果:
人數:1
性別:男性
年齡:青年
身體朝向:正面
下半身服飾:不確定
下半身衣着顏色:黑
上半身服飾:不確定
上半身衣着顏色:綠
上身服飾分類:長袖
上身服飾紋理:純色
是否戴眼鏡:無眼鏡
是否戴帽子:無帽
是否吸菸:未吸菸
交通工具:無交通工具
使用手機:未使用手機
是否撐傘:未打傘
揹包:無揹包
2.3
完整識別結果:
人數:1
性別:男性
年齡:青年
身體朝向:正面
下半身服飾:長褲
下半身衣着顏色:黑
上半身服飾:長褲
上半身衣着顏色:灰
上身服飾分類:長袖
上身服飾紋理:純色
是否戴眼鏡:無眼鏡
是否戴帽子:無帽
是否吸菸:未吸菸
交通工具:無交通工具
使用手機:未使用手機
是否撐傘:未打傘
揹包:無揹包
根據識別結果可以看出,該接口對於性別、服飾、服飾類型、顏色等的識別比較準確,但是對於是否吸菸、是否戴眼鏡等識別就比較差了,還需要再改進。