C#实现控制台传参调用YoloV5模型进行人体识别

一、项目地址

  https://gitee.com/qq28069933146_admin/yoloconsole_body

二、代码解析

1、获取输入参数

//static void Main(string[] args)方法中运行如下代码:
string toBeTestedImgPathStr = AppContext.BaseDirectory + "\\test.jpg";
if (args.Length > 0)
{
    toBeTestedImgPathStr = args[0];
}

2、C#加载YoloV5的onnx模型

YoloScorer<YoloCocoP5Model> scorer = new YoloScorer<YoloCocoP5Model>(modelPath);  // 选择模型

3、使用YoloV5模型进行预测

List<YoloPrediction> predictions = scorer.Predict(image);  // 预测

4、自定义人体信息类

  该类用于在控制台打印人体位置信息

    /// <summary>
    /// 人体信息
    /// </summary>
    public class BodyInfo
    {
        public int Left { get; set; } = 0;
        public int Top { get; set; } = 0;
        public int Right { get; set; } = 0;
        public int Bottom { get; set; } = 0;

        /// <summary>
        /// 概率
        /// </summary>
        public double Score { get; set; } = 0;

        public BodyInfo(int left, int top, int right, int bottom, double score)
        {
            Left = left;
            Top = top;
            Right = right;
            Bottom = bottom;
            Score = score;
        }
    }

5、用BodyInfo保存人体信息并在图片上标注人体位置

  // 保存人体位置信息
  List<BodyInfo> bodyInfos = new List<BodyInfo>();

  // 标注图片
  foreach (YoloPrediction prediction in predictions)
  {
      if (prediction.Label.Name == "person")  // prediction.Label.Id == "1"
      {
          double score = Math.Round(prediction.Score, 2);                               // 概率(保留两位小数)
          var (x, y) = (prediction.Rectangle.Left - 3, prediction.Rectangle.Top - 23);  // 标注信息的位置信息

          // 标说明
          image.Mutate(a => a.DrawText($"{prediction.Label.Name} ({score})",
                          font, prediction.Label.Color, new PointF(x, y)));

          // 框位置
          image.Mutate(a => a.DrawPolygon(prediction.Label.Color, 1,
              new PointF(prediction.Rectangle.Left, prediction.Rectangle.Top),
              new PointF(prediction.Rectangle.Right, prediction.Rectangle.Top),
              new PointF(prediction.Rectangle.Right, prediction.Rectangle.Bottom),
              new PointF(prediction.Rectangle.Left, prediction.Rectangle.Bottom)
              ));

          bodyInfos.Add(new BodyInfo((int)prediction.Rectangle.Left, (int)prediction.Rectangle.Top, (int)prediction.Rectangle.Right, (int)prediction.Rectangle.Bottom, score));
      }
  }

6、保存图片

image.SaveAsync(toBeTestedImgNewNameStr);

7、控制台输出结果(json字符串格式)

string resultStr = JsonConvert.SerializeObject(bodyInfos);

Console.WriteLine(resultStr);

8、运行效果

  控制台调用,输入参数即可(如:YoloConsole.exe -E:);效果如下:

posted @   ꧁执笔小白꧂  阅读(447)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
点击右上角即可分享
微信分享提示