C# 使用 Yolov5 模型識別物品

@zgcwkj  2023年08月20日

分類:

代碼 網站 

C# 使用 ONNX 格式的模型,完成 AI 識別(機器學習筆記

模型查看

  1. Netron

模型輸入(圖片轉張量)

/// <summary>
/// 計算張量(RRRR GGGG BBBB)
/// </summary>
/// <param name="source">圖像</param>
/// <returns></returns>
public static Tensor<float> FastToOnnxTensor(SKBitmap source)
{
    var tensorShape = new int[] { 1, 3, source.Height, source.Width };
    var tensor = new DenseTensor<float>(tensorShape);

    for (int y = 0; y < source.Height; y++)
    {
        for (int x = 0; x < source.Width; x++)
        {
            var pixel = source.GetPixel(x, y);
            tensor[0, 0, y, x] = pixel.Red / 255f; // R
            tensor[0, 1, y, x] = pixel.Green / 255f; // G
            tensor[0, 2, y, x] = pixel.Blue / 255f; // B
        }
    }

    return tensor;
}

模型輸出(張量計算坐標)

/// <summary>
/// 解析結果
/// </summary>
/// <param name="results">計算後的張量</param>
/// <returns></returns>
private List<Prediction> ParseResults(float[] results)
{
    //邊界框長度
    int confidenceIndex = 4;
    //置信度長度
    int labelStartIndex = 5;
    //標簽數量
    int labelLength = _YoloLabes.Length;
    //每個分區長度
    int dimensions = labelLength + 5;
    //分區數量
    int rows = results.Length / dimensions;
    //
    var detections = new List<Prediction>();
    for (int i = 0; i < rows; ++i)
    {
        var index = i * dimensions;
        //不要置信度低的
        if (results[index + confidenceIndex] <= 0.4f) continue;
        //對每個預測類別的置信度進行縮放
        for (int j = labelStartIndex; j < dimensions; ++j)
        {
            results[index + j] = results[index + j] * results[index + confidenceIndex];
        }
        //分析每個預測類別
        for (int k = labelStartIndex; k < dimensions; ++k)
        {
            //不要過低的預測類別
            if (results[index + k] <= 0.5f) continue;

            var value_0 = results[index];
            var value_1 = results[index + 1];
            var value_2 = results[index + 2];
            var value_3 = results[index + 3];

            var bbox = new BBox(
                (value_0 - value_2 / 2) / _YoloWidth,
                (value_1 - value_3 / 2) / _YoloWidth,
                (value_0 + value_2 / 2) / _YoloHeight,
                (value_1 + value_3 / 2) / _YoloHeight);

            var l_index = k - labelStartIndex;
            detections.Add(new Prediction()
            {
                Box = bbox,
                Confidence = results[index + k],
                LabelIndex = l_index,
                LabelName = _YoloLabes[l_index]
            });
        }
    }

    return Prediction.NMS(detections);
}

示例項目

  1. 源碼:AiYoloV5Onnx.7z
    內容已隱藏,需要評論並且審核通過後,才能閱讀隱藏內容


評論已關閉

Top