使用百度AI技術(shù)進行圖片車輛分割提取

【使用攻略】【車輛分析】車輛分割

一、需求描述

如果是簡單的將一張圖片中的汽車輪廓給摳出來,形成一張透明背景汽車摳圖,這個目前感覺還沒有太大的運用空間,畢竟這一步好像僅僅代替了人工PS摳圖,采取了自動摳圖,摳圖后的效果也不是很好(大部分圖片不能直接拿來當(dāng)效果圖使用),不過如果在車輛分割的基礎(chǔ)上,進行一定的升級改進,相信會有很大的應(yīng)用價值的。

二、使用攻略

說明:本文采用C# 語言,開發(fā)環(huán)境為.Net Core 2.1,采用在線API接口方式實現(xiàn)。

(1)平臺接入

目前處于邀測階段,不能直接在控制臺調(diào)用,可通過QQ群(659268104)聯(lián)系群管、或提交工單申請開通測試權(quán)限。

(2)接口文檔

文檔地址:https://ai.baidu.com/docs#/ImageClassify-API/3e953ab4


接口描述:傳入單幀圖像,檢測圖像中的車輛,以小汽車為主,識別車輛的輪廓范圍,與背景進行分離,返回分割后的二值圖、灰度圖、前景摳圖,支持多個車輛、車門打開、后備箱打開、機蓋打開、正面、側(cè)面、背面等各種拍攝場景。

請求說明

返回說明


(3)源碼共享


3.1-根據(jù) 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.2-調(diào)用API接口獲取識別結(jié)果


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、建立Index.cshtml文件


2.1 前臺代碼:

??? 由于html代碼無法原生顯示,只能簡單說明一下:

??? 主要是一個form表單,需要設(shè)置屬性enctype="multipart/form-data",否則無法上傳圖片;

??? form表單里面有四個控件:

??? 一個Input:type="file",asp-for="FileUpload" ,上傳圖片用;

??? 一個Input:type="submit",asp-page-handler="VehicleSeg" ,提交并返回識別結(jié)果。

??? 一個img:src="@Model.curPath",顯示需要識別的圖片。

??? 一個img:src="@Model.imgProcessPath",顯示車輛分割后的前景摳圖。

??? 最后顯示后臺 msg 字符串列表信息,如果需要輸出原始Html代碼,則需要使用@Html.Raw()函數(shù)。

2.2 后臺代碼:

[BindProperty]

public IFormFile FileUpload { get; set; }

[BindProperty]

public string ImageUrl { get; set; }

private readonly IHostingEnvironment HostingEnvironment;

public List msg = new List();

public string curPath { get; set; }

public string imgProcessPath { get; set; }

public ImageProcessModel(IHostingEnvironment hostingEnvironment)

{

HostingEnvironment = hostingEnvironment;

}

public async Task OnPostVehicleSegAsync()

{

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 = GetImageJson(imgBase64,?“你的API KEY”, “你的SECRET KEY”, "foreground");

JObject jo = (JObject)JsonConvert.DeserializeObject(result);

try

{

string imageProcessBase64 = jo["foreground"].ToString();

msg.Add("車輛分割");

msg.Add("log_id:" + jo["log_id"].ToString());

string processImgName = Guid.NewGuid().ToString("N")+ ".png";

string imgSavedPath = Path.Combine(webRootPath,

"Uploads//BaiduAIs//", processImgName);

imgProcessPath = Path.Combine(

"BaiduAIs//", processImgName);

await GetFileFromBase64(imageProcessBase64, imgSavedPath);

}

catch (Exception e)

{

msg.Add(result);

}

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;

}

///

/// 文件base64解碼

///

/// 文件base64編碼

/// 生成文件路徑

public static async Task GetFileFromBase64(string base64Str, string outPath)

{

var contents = Convert.FromBase64String(base64Str);

using (var fs = new FileStream(outPath, FileMode.Create, FileAccess.Write))

{

fs.Write(contents, 0, contents.Length);

fs.Flush();

}

}

///

/// 圖像識別Json字符串

///

/// 圖片base64編碼

/// API Key

/// Secret Key

///

public static string GetImageJson(string strbaser64, string clientId, string clientSecret, string type)

{

string token = GetAccessToken(clientId, clientSecret);

string host = "https://aip.baidubce.com/rest/2.0/image-classify/v1/vehicle_seg?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)+"&type=" + type;

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、識別結(jié)果:

2.1

2.2

2.3

2.4

四、產(chǎn)品建議

1、自動補全功能

首先,關(guān)于前景摳圖的輪廓處理,目前好像對其進行了一定的模糊處理,但是這種處理方法不是很好,如果能夠使用AI的自動學(xué)習(xí)能力,根據(jù)輸入的圖片,搜索相似的車輛圖片,然后對其進行自動補全操作,比如一輛車,它的一個輪胎被東西遮擋住了,如果單純分割,分割后的圖片中的車子是少一半輪胎的,這時候,如果能夠結(jié)合AI學(xué)習(xí)技術(shù),根據(jù)相似的車輛圖片,對那缺失的一半輪胎進行修圖補全,形成一個完整的車輛圖片,那么,最后的摳圖就有更大的價值了。

2、效果美化

對車輛圖片進行補全后,若能夠根據(jù)相似圖,對摳圖進行一定的美化功能(類似現(xiàn)在流行的美顏相機),那么美化后的摳圖就是一張相當(dāng)好的效果圖,這樣的話,就可以直接拿來當(dāng)宣傳圖使用了。當(dāng)然,美化訓(xùn)練,可以采取對大量的車輛圖片進行打分,最后獲取高分車輛圖片,然后讓AI學(xué)習(xí)如何將圖像往高分圖方向美化,這樣美化后的圖片就比較符合大眾要求了。

3、多圖錄入,形成三維效果圖

另外,如果能夠?qū)崿F(xiàn)對一輛車,進行前、后、左、右多方位拍圖并輸入系統(tǒng),最后根據(jù)輸入的圖片,結(jié)合該車輛已存在的設(shè)計圖等進行模擬計算,輸出該車的三維效果圖的話,運用前景就很大了。

3.1、結(jié)合百度AR技術(shù),顯示三維效果圖

比如,可以結(jié)合百度AR技術(shù),將車輛三維效果圖顯示到自己想要顯示的地方,這樣的話,不僅可以讓汽車銷售員直接出去推銷車輛,在汽車銷售介紹的時候,顯示三維效果圖讓顧客能夠全方向的了解車輛,還能讓汽車愛好者收集自己喜歡的車輛,并跟車友們很好的進行分享交流。

3.2、結(jié)合3D打印技術(shù),打印三維車輛模型

還可以結(jié)合3D打印技術(shù),直接打印出車輛的模型。如果能夠?qū)σ惠v車進行多方位拍照,然后運用百度AI技術(shù)進行3D建模,使用3D打印技術(shù)直接打印出該車輛的模型,那是一件很了不起的事情。3D模型不僅可以當(dāng)作小孩子們的玩具,也可以方便汽車愛好者們研究,還有利于汽車銷售,讓顧客有更加直觀的了解。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容