C#用emgu tf预测minst图片类别

using System;
using Emgu.TF.Lite;
using System.Drawing;
using Emgu.CV;
using Emgu.CV.Structure;
using System.Drawing;
namespace Emgus
{
    class Program
    {
        public static void ReadTensorFromMatBgr(Mat image, Tensor tensor, int inputHeight = -1, int inputWidth = -1, float inputMean = 0.0f, float scale = 1.0f)
        {
            Emgu.CV.CvEnum.DepthType depth = image.Depth;
            if (!(depth == Emgu.CV.CvEnum.DepthType.Cv8U || depth == Emgu.CV.CvEnum.DepthType.Cv32F))
            {
                throw new ArgumentException("Input image must be 8U or 32F");
            }
            int finalHeight = inputHeight == -1 ? image.Height : inputHeight;
            int finalWidth = inputWidth == -1 ? image.Width : inputWidth;
            Size finalSize = new Size(finalWidth, finalHeight);

            if (image.Size != finalSize)
            {
                using (Mat tmp = new Mat())
                {
                    CvInvoke.Resize(image, tmp, finalSize);
                    ReadTensorFromMatBgr(tmp, inputMean, scale, tensor);
                    tmp.Dispose();
                }
            }
            else
            {
                ReadTensorFromMatBgr(image, inputMean, scale, tensor);
            }
        }
        private static void ReadTensorFromMatBgr(Mat image, float inputMean, float scale, Tensor t)
        {
            DataType type = t.Type;
            if (type == DataType.Float32)
            {
                using (Mat matF = new Mat(image.Size, Emgu.CV.CvEnum.DepthType.Cv32F, 3, t.DataPointer, sizeof(float) * 3 * image.Width))
                {
                    image.ConvertTo(matF, Emgu.CV.CvEnum.DepthType.Cv32F);
                }
            }
            else if (type == DataType.UInt8)
            {
                using (Mat matB = new Mat(image.Size, Emgu.CV.CvEnum.DepthType.Cv8U, 3, t.DataPointer, sizeof(byte) * 3 * image.Width))
                {
                    if (scale == 1.0f && inputMean == 0)
                    {
                        image.CopyTo(matB);
                    }
                    else
                        CvInvoke.ConvertScaleAbs(image, matB, scale, -inputMean * scale);
                }
            }
            else
            {
                throw new Exception(String.Format("Data Type of {0} is not supported.", type));
            }
        }
        static void Main(string[] args)
        {
            String imageFile = "1.jpg";
            String modelDir = "mnist.tflite";
            Interpreter interpreter = new Interpreter(new FlatBufferModel(modelDir));
            interpreter.AllocateTensors();
            var inputTensor = interpreter.Inputs[0];
            var outputTensor = interpreter.Outputs[0];
            Mat img = CvInvoke.Imread(imageFile);
            CvInvoke.Resize(img, img, new Size(28, 28));
            if (img.Depth != Emgu.CV.CvEnum.DepthType.Cv32F)
            {
                img.ConvertTo(img, Emgu.CV.CvEnum.DepthType.Cv32F);
                img /= 255;
            }
            ReadTensorFromMatBgr(
            image: img,
            tensor: inputTensor,
            inputHeight: 28,
            inputWidth: 28
            );
            interpreter.Invoke();
            Console.WriteLine(outputTensor);
            Array result = outputTensor.Data;
            int index = -1;
            float value = -1f;
            for (int i = 0; i < result.Length; i++)
            {
                float temp = (float)Convert.ToSingle(result.GetValue(i));
                if (temp > value)
                {
                    index = i;
                    value = temp;
                }
                Console.WriteLine(result.GetValue(i));
            }
            Console.WriteLine(index);
            Console.WriteLine(value);
            Console.ReadKey();
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Emgu.TF.Lite;
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Linq;
using Emgu.Models;
string imageFile = "1.jpg";
String modelDir = "mnist.tflite";
int width = 28;
int height = 28;
float mean = 0.0f;
float scale = 1.0f;
bool flipUpsideDown = false;
bool swapBR = true;
Interpreter interpreter = new Interpreter(new FlatBufferModel(modelDir));
interpreter.AllocateTensors();
int[] input = interpreter.InputIndices;
var inputTensor = interpreter.Inputs[0];
int[] output = interpreter.InputIndices;
var outputTensor = interpreter.Outputs[0];
NativeImageIO.ReadImageFileToTensor<float>(imageFile, inputTensor.DataPointer, height, width, mean, scale, flipUpsideDown, swapBR);
interpreter.Invoke();

float[] outputData = outputTensor.Data as float[];
string[] classNames = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };

int index;
float a = Softmax(outputData, out index);
Console.WriteLine($"The image has been predicted as {classNames[index]} with probability of {a:N2}%.");

Console.WriteLine(outputData);
Console.ReadKey();
static float Softmax(float[] data, out int index)
{
    var l = data.Length;
    float[] expData = new float[l];
    float sum = 0;
    for (int i = 0; i < l; i++) expData[i] = (float)Math.Exp(data[i]);
    foreach (var item in expData) sum += item;
    for (int i = 0; i < l; i++) expData[i] /= sum;
    index = expData.ToList<float>().IndexOf(expData.Max());
    return expData.Max() * 100;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值