【百度大脑新品体验】车辆分割

一、需求描述

从实拍图中自动分割出汽车图像,实现自动批量抠图,可进一步对背景图像进行替换、合成、虚化处理,用于新车、二手车宣传图制作。

二、使用攻略

说明:本文采用C# 语言,开发环境为.Net Core 2.1,采用在线API接口方式实现。
(1)平台接入
目前处于邀测阶段,不能直接在控制台调用,可通过QQ群(659268104)联系群管、或提交工单申请开通测试权限。
(2)接口文档
文档地址:https://ai.baidu.com/docs#/ImageClassify-API/3e953ab4

接口描述:传入单帧图像,检测图像中的车辆,以小汽车为主,识别车辆的轮廓范围,与背景进行分离,返回分割后的二值图、灰度图、前景抠图,支持多个车辆、车门打开、后备箱打开、机盖打开、正面、侧面、背面等各种拍摄场景。
请求说明
在这里插入图片描述
在这里插入图片描述

返回说明
在这里插入图片描述

(3)源码共享

3.1-根据 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-调用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、 建立Index.cshtml文件

2.1 前台代码: 由于html代码无法原生显示,只能简单说明一下:

主要是一个form表单,需要设置属性enctype="multipart/form-data",否则无法上传图片;

form表单里面有四个控件:

一个Input:type="file",asp-for="FileUpload" ,上传图片用;

一个Input:type="submit",asp-page-handler="VehicleSeg" ,提交并返回识别结果。

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

一个img:src="@Model.imgProcessPath",显示车辆分割后的前景抠图。

最后显示后台 msg 字符串列表信息,如果需要输出原始Html代码,则需要使用@Html.Raw()函数。

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、识别结果:

2.1
在这里插入图片描述

2.2
在这里插入图片描述

2.3
在这里插入图片描述

2.4
在这里插入图片描述

四、测试结果

总体来说,车辆分割效果的好坏,跟照片中车辆环境还是有较大的关系的,如果车辆跟周围环境区别比较明细,则分割效果相当好,如果车辆跟周围环境区别不太明显,则分割效果就不稳定了。可以尝试优化当车辆跟周围环境较为相似时,如何采取更好的方法进行车辆分割:比如,可以先识别出当前车辆类型,然后根据该车辆类型的模型图,去进行分割等。

另外,可以加入一下功能,增强车辆分割技术:

1、自动补全功能

首先,关于前景抠图的轮廓处理,目前好像对其进行了一定的模糊处理,但是这种处理方法不是很好,如果能够使用AI的自动学习能力,根据输入的图片,搜索相似的车辆图片,然后对其进行自动补全操作,比如一辆车,它的一个轮胎被东西遮挡住了,如果单纯分割,分割后的图片中的车子是少一半轮胎的,这时候,如果能够结合AI学习技术,根据相似的车辆图片,对那缺失的一半轮胎进行修图补全,形成一个完整的车辆图片,那么,最后的抠图就有更大的价值了。

2、效果美化

对车辆图片进行补全后,若能够根据相似图,对抠图进行一定的美化功能(类似现在流行的美颜相机),那么美化后的抠图就是一张相当好的效果图,这样的话,就可以直接拿来当宣传图使用了。当然,美化训练,可以采取对大量的车辆图片进行打分,最后获取高分车辆图片,然后让AI学习如何将图像往高分图方向美化,这样美化后的图片就比较符合大众要求了。

3、多图录入,形成三维效果图

另外,如果能够实现对一辆车,进行前、后、左、右多方位拍图并输入系统,最后根据输入的图片,结合该车辆已存在的设计图等进行模拟计算,输出该车的三维效果图的话,运用前景就很大了。

3.1、结合百度AR技术,显示三维效果图

比如,可以结合百度AR技术,将车辆三维效果图显示到自己想要显示的地方,这样的话,不仅可以让汽车销售员直接出去推销车辆,在汽车销售介绍的时候,显示三维效果图让顾客能够全方向的了解车辆,还能让汽车爱好者收集自己喜欢的车辆,并跟车友们很好的进行分享交流。

3.2、结合3D打印技术,打印三维车辆模型

还可以结合3D打印技术,直接打印出车辆的模型。如果能够对一辆车进行多方位拍照,然后运用百度AI技术进行3D建模,使用3D打印技术直接打印出该车辆的模型,那是一件很了不起的事情。3D模型不仅可以当作小孩子们的玩具,也可以方便汽车爱好者们研究,还有利于汽车销售,让顾客有更加直观的了解。

发布了10 篇原创文章 · 获赞 4 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_45449540/article/details/103634283