【深度学习主题月】EasyDL物体检测智能标注
让天涯 发布于2019-10 浏览:3509 回复:3
0
收藏
最后编辑于2022-04

一、功能介绍

零算法基础训练业务定制物体检测模型,可识别图中每个物体的位置、名称,适合有多个主体、或要识别位置及数量的场景。

二、使用场景

1、结合内容审核平台,进行自定义图像审核过滤。
2、标识所给图片中的所有目标物体名称、位置。
3、在企业生产过程中,可以在产品质量检测方面发挥作用:通过对成品、合格品、不合格品的模型创建训练,拍照识别出当前检测的产品是否合格、质量是否过关,大大减少人工检测成本,提高质量检测效率;同时,也可以在产品数量统计方面发挥作用,拍照统计产品数量,大大降低人工统计的成本,提高统计效率。
三、使用攻略

(1)平台接入
登陆 百度智能云-管理中心 创建 “EasyDL定制化物体检测”应用,获取 “API Key ”和 “Secret Key”:https://console.bce.baidu.com/ai/?_=1537962688426&ed&no_xss&locale=zh-cn#/ai/easydl/overview/index
(2)接口文档

文档地址(经典版):https://ai.baidu.com/docs#/EasyDL_VIS_Detection_Intro/top

文档地址(专业版):https://ai.baidu.com/docs#/EasyDL_Pro_VIS_Intro/top

接口描述:检测图中每个物体的位置、名称。适合图中有多个主体要识别、或要识别主体位置及数量的场景。

(3)源码共享
说明:本文采用C# 语言,开发环境为 .Net Core 2.2,采用在线API接口方式实现,需要用到 SixLabors.ImageSharp 和 SixLabors.ImageSharp.Drawing NuGet程序包来对图片进行画框标识,另外,还需要复制一个字体文件到 wwwroot 文件夹下,方便在图片上写文字内容,本程序所用的字体为simhei.ttf。

具体关于如何创建EasyDL定制化物体检测模型并结合内容审核平台进行图片审核过滤的步骤,可以参考我以前写的文章,这里就不再重复了:https://ai.baidu.com/forum/topic/show/956164

EasyDL专业版的物体检测模型的创建过程跟定制版相差不大,基本上就是选择选型,所以这里也就不再一一描述了,最后会比较一下EasyDL经典版和专业版两者的不同之处。

本程序所用的数据集是源于同一数据集,是在经典版中进行创建标注的,专业版可以直接拿来使用。

在模型发布后,EasyDL经典版可以在【我的模型】页面下,选择【服务详情】获取在线API接口:https://ai.baidu.com/easydl/app/2/models

而对于EasyDL专业版,可以在【我的服务】中,点击【服务详情】,获取在线API接口地址:https://ai.baidu.com/easydl/pro/app/dashboard

在线AIP接口地址在程序调用的时候会用到。

示例代码展示了如何将发布的模型整合到自己的应用中去。

(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接口获取识别结果

(3-2-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"
});

(3-2-2) 建立Index.cshtml文件

(3-2-2-1)前台代码:

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

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

    form表单里面有几个控件:

一个Input:type="file",asp-for="FileUpload" ,上传图片;
一个Input:type="submit",asp-page-handler="AnimalEasyDL" ,EasyDL物体检测经典版识别。
一个Input:type="submit",asp-page-handler="AnimalProEasyDL" ,EasyDL物体检测专业版识别。
一个img:src="@Model.curPath",显示识别后的图片。

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

(3-2-2-2) 后台代码: 

首先,建立一个矩形文字类Rectangle,存储画图所需的内容:

/// 
/// 矩形文字数据
/// 
public class Rectangle
{
    /// 
    /// X坐标
    /// 
    [Display(Name = "X坐标")]
    public float X { get; set; }
    /// 
    /// Y坐标
    /// 
    [Display(Name = "Y坐标")]
    public float Y { get; set; }
    /// 
    /// 宽度
    /// 
    [Display(Name = "宽度")]
    public float Width { get; set; }
    /// 
    /// 高度
    /// 
    [Display(Name = "高度")]
    public float Height { get; set; }
    /// 
    /// 线条颜色
    /// 
    [Display(Name = "线条颜色")]
    public Color LineColor { get; set; }
    /// 
    /// 线条厚度
    /// 
    [Display(Name = "线条厚度")]
    public float Thinkness { get; set; }

    /// 
    /// 字体文件
    /// 
    public string FontPath { get; set; }
    /// 
    /// 文字位置
    /// 
    public Vector2 FontLocation { get; set; }
    /// 
    /// 字体大小
    /// 
    public float FontSize { get; set; }
    /// 
    /// 字体颜色
    /// 
    public Color FontColor { get; set; }
    /// 
    /// 文字内容
    /// 
    public string FontContent { get; set; }


    /// 
    /// 上左点坐标
    /// 
    [Display(Name = "上左点坐标")]
    public Vector2 point1
    {
        get
        {
            return new Vector2(X, Y);
        }
    }
    /// 
    /// 上右点坐标
    /// 
    [Display(Name = "上右点坐标")]
    public Vector2 point2
    {
        get
        {
            return new Vector2(X + Width, Y);
        }
    }
    /// 
    /// 下右点坐标
    /// 
    [Display(Name = "下右点坐标")]
    public Vector2 point3
    {
        get
        {
            return new Vector2(X + Width, Y + Height);
        }
    }
    /// 
    /// 下左点坐标
    /// 
    [Display(Name = "下左点坐标")]
    public Vector2 point4
    {
        get
        {
            return new Vector2(X, Y + Height);
        }
    }

    public Rectangle()
    {

    }

    /// 
    /// 数据初始化
    /// 
    /// X坐标
    /// Y坐标
    /// 宽度
    /// 高度
    /// 字体文件
    /// 文字内容
    public Rectangle(float x, float y, float width, float height, string fontPath, string fontContent)
    {
        X = x;
        Y = y;
        Width = width;
        Height = height;
        LineColor = Color.Red;
        Thinkness = 1;

        FontPath = fontPath;
        FontLocation = new Vector2(x + 5, y + 5);
        FontSize = 30;
        FontColor = Color.Red;
        FontContent = fontContent;
    }
}

主程序代码:

[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; }

string BaiduAI_ImageSearchPath="Uploads//BaiduAIs//";
string BaiduAI_ImageSearchUrl="/BaiduAIs/";
string EasyDL_API_KEY="你的API KEY";
string EasyDL_SECRET_KEY="你的SECRET KEY";
string FontPath="simhei.ttf";

public ImageSearchModel(IHostingEnvironment hostingEnvironment)
{
    HostingEnvironment = hostingEnvironment;
}
public async Task OnPostAnimalEasyDLAsync()
{
    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, BaiduAI_ImageSearchPath);
    string imgName = GetRandomName();
    imgName = await UploadFile(FileUpload, fileDir);

    string fileName = Path.Combine(fileDir, imgName);
    string imgBase64 = GetFileBase64(fileName);

    string fontPaht = Path.Combine(webRootPath, FontPath);

    DateTime startTime = DateTime.Now;

    string result = GetEasyDLJson(imgBase64, EasyDL_API_KEY, EasyDL_SECRET_KEY);

    DateTime endTime = DateTime.Now;
    TimeSpan ts = endTime - startTime;

    JObject jo = (JObject)JsonStringToObj(result);

    try
    {
        if (jo["error_code"] != null)
        {
            msg.Add("调用失败:" + jo["error_code"] + "-" + jo["error_msg"]);
        }
        else
        {
            List msgList = jo["results"].ToList();
            int number = msgList.Count;
            int curNumber = 1;
            msg.Add("EasyDL物体检测经典版识别结果(耗时" + ts.TotalSeconds + "秒):");
            msg.Add("识别信息数:" + number);

            List recList = new List();

            foreach (JToken ms in msgList)
            {
                if (number > 1)
                {
                    msg.Add("第 " + curNumber.ToString() + " 条:");
                }

                string name = ms["name"].ToString();
                float left = float.Parse(ms["location"]["left"].ToString());
                float top = float.Parse(ms["location"]["top"].ToString());
                float width = float.Parse(ms["location"]["width"].ToString());
                float height = float.Parse(ms["location"]["height"].ToString());
                float score = float.Parse(ms["score"].ToString());

                msg.Add("分类名称:" + name);
                msg.Add("置信度:" + score.ToString());
                msg.Add("位置:左:" + left + ",上:" + top + ",宽:" + width + ",高:" + height);

                string fontContent = number > 1 ? curNumber.ToString() + "-" + name : name;
                fontContent += "-" + score.ToString("f3");
                Rectangle rec = new Rectangle(left, top, width, height, fontPaht, fontContent);
                recList.Add(rec);

                curNumber++;
            }
            string imgSourcePath = Path.Combine(webRootPath, BaiduAI_ImageSearchPath, imgName);
            imgName = Common.GetRandomName() + ".png";
            string imgSavedPath = Path.Combine(webRootPath, BaiduAI_ImageSearchPath, imgName);

            await DrawPolygonAndText(imgSourcePath, imgSavedPath, recList);
            curPath = Path.Combine(BaiduAI_ImageSearchUrl, imgName);
        }
    }
    catch (Exception e1)
    {
        msg.Add(result);
    }
    return Page();
}


public async Task OnPostAnimalProEasyDLAsync()
{
    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, BaiduAI_ImageSearchPath);
    string imgName = GetRandomName();
    imgName = await UploadFile(FileUpload, fileDir);

    string fileName = Path.Combine(fileDir, imgName);
    string imgBase64 = GetFileBase64(fileName);

    string fontPaht = Path.Combine(webRootPath, FontPath);

    DateTime startTime = DateTime.Now;

    string result = GetEasyDLProJson(imgBase64, EasyDL_API_KEY, EasyDL_SECRET_KEY);

    DateTime endTime = DateTime.Now;
    TimeSpan ts = endTime - startTime;

    JObject jo = (JObject)JsonStringToObj(result);

    try
    {
        if (jo["error_code"] != null)
        {
            msg.Add("调用失败:" + jo["error_code"] + "-" + jo["error_msg"]);
        }
        else
        {
            List msgList = jo["results"].ToList();
            int number = msgList.Count;
            int curNumber = 1;
            msg.Add("EasyDL物体检测专业版识别结果(耗时" + ts.TotalSeconds + "秒):");
            msg.Add("识别信息数:" + number);

            List recList = new List();

            foreach (JToken ms in msgList)
            {
                if (number > 1)
                {
                    msg.Add("第 " + curNumber.ToString() + " 条:");
                }

                string name = ms["name"].ToString();
                float left = float.Parse(ms["location"]["left"].ToString());
                float top = float.Parse(ms["location"]["top"].ToString());
                float width = float.Parse(ms["location"]["width"].ToString());
                float height = float.Parse(ms["location"]["height"].ToString());
                float score = float.Parse(ms["score"].ToString());

                msg.Add("分类名称:" + name);
                msg.Add("置信度:" + score.ToString());
                msg.Add("位置:左:" + left + ",上:" + top + ",宽:" + width + ",高:" + height);

                string fontContent = number > 1 ? curNumber.ToString() + "-" + name : name;
                fontContent += "-" + score.ToString("f3");
                Rectangle rec = new Rectangle(left, top, width, height, fontPaht, fontContent);
                recList.Add(rec);

                curNumber++;
            }
            string imgSourcePath = Path.Combine(webRootPath, BaiduAI_ImageSearchPath, imgName);
            imgName = GetRandomName() + ".png";
            string imgSavedPath = Path.Combine(webRootPath, BaiduAI_ImageSearchPath, imgName);

            await Common.DrawPolygonAndText(imgSourcePath, imgSavedPath, recList);
            curPath = Path.Combine(BaiduAI_ImageSearchUrl, imgName);
        }
    }
    catch (Exception e1)
    {
        msg.Add(result);
    }
    return Page();
}

 其他相关函数:

/// 
/// 生成一个随机唯一文件名(Guid)
/// 
/// 
public static string GetRandomName()
{
    return Guid.NewGuid().ToString("N");
}

/// 
/// json转为对象
/// 
/// Json字符串
/// 
public static Object JsonStringToObj(string jsonString)
{
    Object s = JsonConvert.DeserializeObject(jsonString);
    return s;
}

/// 
/// 上传文件,返回文件名
/// 
/// 文件上传控件
/// 文件绝对路径
/// 
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;
}

/// 
/// EasyDL定制训练平台Json字符串(经典版)
/// 
/// 图片base64编码
/// API Key
/// Secret Key
/// 
public static string GetEasyDLJson(string strbaser64, string clientId, string clientSecret)
{
    string token = GetAccessToken(clientId, clientSecret);
    string host = "你的在线API接口地址?access_token=" + token;
    Encoding encoding = Encoding.Default;
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
    request.Method = "post";
    request.ContentType = "application/json";
    request.KeepAlive = true;
    string str = "{\"image\":\"" + 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;
}

/// 
/// EasyDL定制训练平台Json字符串(专业版)
/// 
/// 图片base64编码
/// API Key
/// Secret Key
/// 
public static string GetEasyDLProJson(string strbaser64, string clientId, string clientSecret)
{
    string token = GetAccessToken(clientId, clientSecret);
    string host = "你的在线API接口地址?access_token=" + token;
    Encoding encoding = Encoding.Default;
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
    request.Method = "post";
    request.ContentType = "application/json";
    request.KeepAlive = true;
    string str = "{\"image\":\"" + 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;
}

/// 
/// 画矩形
/// 
/// 原图
/// 目标图
/// 矩形数据
public static async Task DrawPolygonAndText(string originalPath, string targetPath, List recList)
{
    using (Image image = Image.Load(originalPath))
    {
        foreach (Rectangle rec in recList)
        {
            image.Mutate(
                x => x.DrawPolygon(
                    rec.LineColor,
                    rec.Thinkness,
                    rec.point1, rec.point2, rec.point3, rec.point4));

            var install_Family = new FontCollection().Install(rec.FontPath);
            var font = new Font(install_Family, rec.FontSize);

            image.Mutate(x => x
                 .DrawText(
                rec.FontContent,
                font,
                rec.FontColor,
                rec.FontLocation));
        }
        image.Save(targetPath);
    }
}

 

四、效果测试

1、页面:

2、识别结果:

2.1

2.2

2.3

2.4

2.5

五、测试结果及建议

通过上面的测试可知,EasyDL经典版和专业版在使用步骤上基本一样,都需要先上传数据、标注数据(可选择智能标注),之后,创建模型(项目)并进行相应的配置进行训练,等训练完成后,就能部署使用了,这样的好处是,只要会了其中一个,另一个也能很快掌握。
此外,两个两个版本都支持在线API、离线服务和本地部署。

当然,EasyDL经典版和专业版还是存在一些不同的:
首先,两者支持的模型类型有所不同(目前):经典版支持图像分类、物体检测、图像分割、文本分类、视频分类、声音分类 ;专业版暂时只支持图像分类、物体检测 、文本分类、短文本匹配 ,不过相信不久后专业版会支持更多的模型类型的。
其次,两者所使用的训练所使用的算法也是不同的,每个版本也有不同的算法可以选择,比如,对于物体检测模型来说:经典版有云服务和离线服务两种,其中,云服务可以选择高精度、高性能的算法;专业版有Faster_R-CNN-ResNet50-FPN、YOLOv3-DarkNet、SSD-MobileNet 三种算法可以选择(不过我创建任务时,好像只有YOLOv3-DarkNet、SSD-MobileNet 两种算法可以选择)。这个可能比较专业,我就不仔细说了,有时间会选择不同算法分别做个比较测试,直接看识别速度和精确度会有个更加直观的感受。
此外,EasyDL专业版还支持飞桨(Paddle Paddle)深度学习框架,EasyDL专业版为每一种预训练模型都预置了脚本代码,在不需要修改的情况下可直接启动训练,当然,也提供了自定义脚本的功能,可以让开发者进行自定义配置,以获取更好的效果,这应该是EasyDL专业版跟经典版最大的区别了。
另外,在经典版中创建、标注的数据集,专业版默认将其同步过来了,所以无需重复创建、标注一样的数据集了,这个相当方便,减少了将经典版升级到专业版的顾虑,毕竟标注数据是相当繁琐的一个步骤(虽然有了智能标注)。
在实际操作中,经典版和专业版还有一个区别,那就是在上传数据集的时候,经典版每次只能选择20张图片上传,而专业版每次可以选择100张图片上传,相差了整整5倍,图片多的话,这是一个很大的差距的,而想让模型获取更加好的效果,那图片的数量肯定是不少的。。。
当然,对于EasyDL专业版来说,这可能不是问题,因为专业版可以选择上传5G内的ZIP图片压缩包。。。

最后,再比较一下EasyDL经典版和专业版的识别效果吧(本程序,经典版选择了云服务高性能算法、专业版选择了SSD-MobileNet算法):
从上面的识别图片可知,EasyDL专业版不论是识别速度、识别置信度还是识别准确度都比EasyDL经典版要好很多:
在识别速度上,专业版几乎要比经典版快了一倍多;
识别的矩形位置,专业版也比经典版要更加的准确。
有时候,经典版会将一个物体识别成两个物体(图2.2),或将物体识别成错误的其他比较类似的物体(图2.3,2.5),或将两个物体识别成3个物体(2.4),而专业版却没有这个错误。

从这个使用来说,EasyDL专业版在各方便都比经典版要有不少的提升,而且操作也没有更加复杂,不过支持的模型类型还没有经典版多,希望今后能够提供 更多的模型类型。
另外,在数据集创建上,启用智能标注的时候,在智能标注筛选需要优先标注的时候,能不能显示一个大致筛选结束时间,现在发现,智能标注筛选时间肯定不短,但是具体需要多长时间又不确定,这个等待时间比较让人着急,如果能够显示一个大致筛选结束时间,也会让人更加宽心,如果能够优化减少智能标注的筛选时间就更好了。
另外,如果能将EasyDL的经典版数据集和专业版数据集同步起来就更好了,那么不管在哪个版本里创建的数据集,都是共享使用,相当方便。

收藏
点赞
0
个赞
共3条回复 最后由用户已被禁言回复于2022-04
#4worddict回复于2019-12

写的很详细

0
#3wangwei8638回复于2019-12

提高了识别率

0
#2大手拉小手0123回复于2019-12

在这方面的应用还是比较不错的

0
TOP
切换版块