Я использовал модель microsoft ml для обучения некоторых изображений.
обучение завершено, и в обозревателе решений созданы два файла:
MLModel1.consumption.cs
MLModel1.training.cs
как мне интегрироваться с файлами моего проекта?
у меня нет этого zip-архива и текстовых файлов:
private readonly string modelPath = "path/to/your/model.zip";
private readonly string labelPath = "path/to/your/labels.txt";
полный код класса:
using Microsoft.ML;
using Microsoft.ML.Data;
using OpenCvSharp;
using System;
using System.Linq;
namespace ImageAnalayzer
{
public class Analyzing
{
private readonly MLContext mlContext;
private ITransformer model;
private readonly string modelPath = "path/to/your/model.zip";
private readonly string labelPath = "path/to/your/labels.txt";
public Analyzing()
{
mlContext = new MLContext();
LoadModel();
}
private void LoadModel()
{
DataViewSchema inputSchema;
model = mlContext.Model.Load(modelPath, out inputSchema);
}
public string AnalyzeWeatherMap(string imagePath)
{
if (!System.IO.File.Exists(imagePath))
{
return "Error: File does not exist.";
}
// Load the image using OpenCVSharp and preprocess
Mat image = Cv2.ImRead(imagePath, ImreadModes.Color);
if (image.Empty())
{
return "Error: Could not load the image.";
}
// Resize and preprocess image for ML.NET
var resizedImage = image.Resize(new Size(224, 224));
float[] imageData = ConvertMatToFloatArray(resizedImage);
// Create an image data structure
var imageInput = new ImageInputData { Image = imageData };
// Use the model to predict
var predictionEngine = mlContext.Model.CreatePredictionEngine(model);
var prediction = predictionEngine.Predict(imageInput);
// Load labels and interpret results
string[] labels = System.IO.File.ReadAllLines(labelPath);
return $"Prediction: {labels[prediction.PredictedLabelIndex]} with confidence {prediction.Confidence:P2}";
}
private float[] ConvertMatToFloatArray(Mat image)
{
float[] data = new float[224 * 224 * 3];
int index = 0;
for (int y = 0; y < 224; y++)
{
for (int x = 0; x < 224; x++)
{
Vec3b color = image.At(y, x);
data[index++] = color.Item0 / 255.0f;
data[index++] = color.Item1 / 255.0f;
data[index++] = color.Item2 / 255.0f;
}
}
return data;
}
public class ImageInputData
{
[VectorType(1, 224, 224, 3)]
public float[] Image { get; set; }
}
public class ImagePrediction : ImageInputData
{
public float[] Score { get; set; }
[ColumnName("PredictedLabel")]
public uint PredictedLabelIndex { get; set; }
public float Confidence => Score.Max();
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/791 ... s-and-mlmo