About
In this code snippet, we’ll see how to do image classification in C# using the ML.NET machine learning framework.
It provides a user friendly GUI for creating, training and deploying different kinds of machine learning models within Visual Studio. It makes it very quick and easy to add machine learning to your .NET projects.
I knew about ML.NET for some time but just recently decided to try it out and add this “tool” to have in my “toolbelt”. I thought I’d build an image classifier that recognizes different electrical components.
I only trained the model for recognizing resistors and toggle switches to avoid having to collect and sort through hundreds if not thousands of images of various electrical components. Granted this doesn’t make the best component classifier but my main goal was to test out ML.NET.
Prerequisites
Preparing The Data
Machine Learning Model
Code To Run The Model:
namespace ML_Test { internal class Program { static void Main(string[] args) { //Load sample data. var imageBytes = File.ReadAllBytes(@"C:\Users\DTPC\Desktop\test imgs\toggle switch example 1.jpg"); MLModel1.ModelInput sampleData = new MLModel1.ModelInput() { ImageSource = imageBytes, }; //Load model and predict output. var result = MLModel1.Predict(sampleData); var labeledScores = MLModel1.GetSortedScoresWithLabels(result); Console.WriteLine("**************************************** Result ****************************************"); Console.WriteLine(); //Print out the results. foreach (var labeledScore in labeledScores) Console.WriteLine($"Item: {labeledScore.Key} Prediction score: {labeledScore.Value}"); Console.WriteLine(); Console.WriteLine($"Highest scoring result is \"{result.PredictedLabel}\" with a score of {result.Score.Last()}."); Console.WriteLine(); Console.WriteLine("****************************************************************************************"); Console.ReadLine(); } } }