8000 Update samples to .NET 6 (#932) · dotnet/machinelearning-samples@fa027d3 · GitHub
[go: up one dir, main page]

Skip to content

Commit fa027d3

Browse files
authored
Update samples to .NET 6 (#932)
* Update bike rental sample to .NET 6 * Update object detection sample to .NET 6
1 parent 89dbd6f commit fa027d3

File tree

5 files changed

+226
-255
lines changed

5 files changed

+226
-255
lines changed

samples/csharp/getting-started/DeepLearning_ObjectDetection_Onnx/ObjectDetectionConsoleApp/ObjectDetection.csproj

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22

33
<PropertyGroup>
44
<OutputType>Exe</OutputType>
5-
<TargetFramework>net5</TargetFramework>
5+
<TargetFramework>net6.0</TargetFramework>
6+
<ImplicitUsings>enable</ImplicitUsings>
67
</PropertyGroup>
78

89
<ItemGroup>
Lines changed: 113 additions & 129 deletions
Original file line numberDiff line numberDiff line change
@@ -1,148 +1,132 @@
1-
using System;
2-
using System.IO;
3-
using System.Collections.Generic;
4-
using System.Drawing;
1+
using System.Drawing;
52
using System.Drawing.Drawing2D;
6-
using System.Linq;
7-
using Microsoft.ML;
83
using ObjectDetection.YoloParser;
94
using ObjectDetection.DataStructures;
5+
using ObjectDetection;
6+
using Microsoft.ML;
7+
8+
var assetsRelativePath = @"../../../assets";
9+
string assetsPath = GetAbsolutePath(assetsRelativePath);
10+
var modelFilePath = Path.Combine(assetsPath, "Model", "TinyYolo2_model.onnx");
11+
var imagesFolder = Path.Combine(assetsPath, "images");
12+
var outputFolder = Path.Combine(assetsPath, "images", "output");
1013

11-
namespace ObjectDetection
14+
// Initialize MLContext
15+
MLContext mlContext = new MLContext();
16+
17+
try
1218
{
13-
class Program
19+
// Load Data
20+
IEnumerable<ImageNetData> images = ImageNetData.ReadFromFile(imagesFolder);
21+
IDataView imageDataView = mlContext.Data.LoadFromEnumerable(images);
22+
23+
// Create instance of model scorer
24+
var modelScorer = new OnnxModelScorer(imagesFolder, modelFilePath, mlContext);
25+
26+
// Use model to score data
27+
IEnumerable<float[]> probabilities = modelScorer.Score(imageDataView);
28+
29+
// Post-process model output
30+
YoloOutputParser parser = new YoloOutputParser();
31+
32+
var boundingBoxes =
33+
probabilities
34+
.Select(probability => parser.ParseOutputs(probability))
35+
.Select(boxes => parser.FilterBoundingBoxes(boxes, 5, .5F));
36+
37+
// Draw bounding boxes for detected objects in each of the images
38+
for (var i = 0; i < images.Count(); i++)
1439
{
15-
public static void Main()
16-
{
17-
var assetsRelativePath = @"../../../assets";
18-
string assetsPath = GetAbsolutePath(assetsRelativePath);
19-
var modelFilePath = Path.Combine(assetsPath, "Model", "TinyYolo2_model.onnx");
20-
var imagesFolder = Path.Combine(assetsPath, "images");
21-
var outputFolder = Path.Combine(assetsPath, "images", "output");
22-
23-
// Initialize MLContext
24-
MLContext mlContext = new MLContext();
25-
26-
try
27-
{
28-
// Load Data
29-
IEnumerable<ImageNetData> images = ImageNetData.ReadFromFile(imagesFolder);
30-
IDataView imageDataView = mlContext.Data.LoadFromEnumerable(images);
31-
32-
// Create instance of model scorer
33-
var modelScorer = new OnnxModelScorer(imagesFolder, modelFilePath, mlContext);
34-
35-
// Use model to score data
36-
IEnumerable<float[]> probabilities = modelScorer.Score(imageDataView);
37-
38-
// Post-process model output
39-
YoloOutputParser parser = new YoloOutputParser();
40-
41-
var boundingBoxes =
42-
probabilities
43-
.Select(probability => parser.ParseOutputs(probability))
44-
.Select(boxes => parser.FilterBoundingBoxes(boxes, 5, .5F));
45-
46-
// Draw bounding boxes for detected objects in each of the images
47-
for (var i = 0; i < images.Count(); i++)
48-
{
49-
string imageFileName = images.ElementAt(i).Label;
50-
IList<YoloBoundingBox> detectedObjects = boundingBoxes.ElementAt(i);
51-
52-
DrawBoundingBox(imagesFolder, outputFolder, imageFileName, detectedObjects);
53-
54-
LogDetectedObjects(imageFileName, detectedObjects);
55-
}
56-
}
57-
catch (Exception ex)
58-
{
59-
Console.WriteLine(ex.ToString());
60-
}
61-
62-
Console.WriteLine("========= End of Process..Hit any Key ========");
63-
Console.ReadLine();
64-
}
40+
string imageFileName = images.ElementAt(i).Label;
41+
IList<YoloBoundingBox> detectedObjects = boundingBoxes.ElementAt(i);
6542

66-
public static string GetAbsolutePath(string relativePath)
67-
{
68-
FileInfo _dataRoot = new FileInfo(typeof(Program).Assembly.Location);
69-
string assemblyFolderPath = _dataRoot.Directory.FullName;
43+
DrawBoundingBox(imagesFolder, outputFolder, imageFileName, detectedObjects);
7044

71-
string fullPath = Path.Combine(assemblyFolderPath, relativePath);
45+
LogDetectedObjects(imageFileName, detectedObjects);
46+
}
47+
}
48+
catch (Exception ex)
49+
{
50+
Console.WriteLine(ex.ToString());
51+
}
7252

73-
return fullPath;
74-
}
53+
Console.WriteLine("========= End of Process..Hit any Key ========");
7554

76-
private static void DrawBoundingBox(string inputImageLocation, string outputImageLocation, string imageName, IList<YoloBoundingBox> filteredBoundingBoxes)
77-
{
78-
Image image = Image.FromFile(Path.Combine(inputImageLocation, imageName));
79-
80-
var originalImageHeight = image.Height;
81-
var originalImageWidth = image.Width;
82-
83-
foreach (var box in filteredBoundingBoxes)
84-
{
85-
// Get Bounding Box Dimensions
86-
var x = (uint)Math.Max(box.Dimensions.X, 0);
87-
var y = (uint)Math.Max(box.Dimensions.Y, 0);
88-
var width = (uint)Math.Min(originalImageWidth - x, box.Dimensions.Width);
89-
var height = (uint)Math.Min(originalImageHeight - y, box.Dimensions.Height);
90-
91-
// Resize To Image
92-
x = (uint)originalImageWidth * x / OnnxModelScorer.ImageNetSettings.imageWidth;
93-
y = (uint)originalImageHeight * y / OnnxModelScorer.ImageNetSettings.imageHeight;
94-
width = (uint)originalImageWidth * width / OnnxModelScorer.ImageNetSettings.imageWidth;
95-
< F987 span class=pl-s1>height = (uint)originalImageHeight * height / OnnxModelScorer.ImageNetSettings.imageHeight;
96-
97-
// Bounding Box Text
98-
string text = $"{box.Label} ({(box.Confidence * 100).ToString("0")}%)";
99-
100-
using (Graphics thumbnailGraphic = Graphics.FromImage(image))
101-
{
102-
thumbnailGraphic.CompositingQuality = CompositingQuality.HighQuality;
103-
thumbnailGraphic.SmoothingMode = SmoothingMode.HighQuality;
104-
thumbnailGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
105-
106-
// Define Text Options
107-
Font drawFont = new Font("Arial", 12, FontStyle.Bold);
108-
SizeF size = thumbnailGraphic.MeasureString(text, drawFont);
109-
SolidBrush fontBrush = new SolidBrush(Color.Black);
110-
Point atPoint = new Point((int)x, (int)y - (int)size.Height - 1);
111-
112-
// Define BoundingBox options
113-
Pen pen = new Pen(box.BoxColor, 3.2f);
114-
SolidBrush colorBrush = new SolidBrush(box.BoxColor);
115-
116-
// Draw text on image
117-
thumbnailGraphic.FillRectangle(colorBrush, (int)x, (int)(y - size.Height - 1), (int)size.Width, (int)size.Height);
118-
thumbnailGraphic.DrawString(text, drawFont, fontBrush, atPoint);
119-
120-
// Draw bounding box on image
121-
thumbnailGraphic.DrawRectangle(pen, x, y, width, height);
122-
}
123-
}
124-
125-
if (!Directory.Exists(outputImageLocation))
126-
{
127-
Directory.CreateDirectory(outputImageLocation);
128-
}
129-
130-
image.Save(Path.Combine(outputImageLocation, imageName));
131-
}
55+
string GetAbsolutePath(string relativePath)
56+
{
57+
FileInfo _dataRoot = new FileInfo(typeof(Program).Assembly.Location);
58+
string assemblyFolderPath = _dataRoot.Directory.FullName;
13259

133-
private static void LogDetectedObjects(string imageName, IList<YoloBoundingBox> boundingBoxes)
134-
{
135-
Console.WriteLine($".....The objects in the image {imageName} are detected as below....");
60+
string fullPath = Path.Combine(assemblyFolderPath, relativePath);
13661

137-
foreach (var box in boundingBoxes)
138-
{
139-
Console.WriteLine($"{box.Label} and its Confidence score: {box.Confidence}");
140-
}
62+
return fullPath;
63+
}
14164

142-
Console.WriteLine("");
65+
void DrawBoundingBox(string inputImageLocation, string outputImageLocation, string imageName, IList<YoloBoundingBox> filteredBoundingBoxes)
66+
{
67+
Image image = Image.FromFile(Path.Combine(inputImageLocation, imageName));
68+
69+
var originalImageHeight = image.Height;
70+
var originalImageWidth = image.Width;
71+
72+
foreach (var box in filteredBoundingBoxes)
73+
{
74+
// Get Bounding Box Dimensions
75+
var x = (uint)Math.Max(box.Dimensions.X, 0);
76+
var y = (uint)Math.Max(box.Dimensions.Y, 0);
77+
var width = (uint)Math.Min(originalImageWidth - x, box.Dimensions.Width);
78+
var height = (uint)Math.Min(originalImageHeight - y, box.Dimensions.Height);
79+
80+
// Resize To Image
81+
x = (uint)originalImageWidth * x / OnnxModelScorer.ImageNetSettings.imageWidth;
82+
y = (uint)originalImageHeight * y / OnnxModelScorer.ImageNetSettings.imageHeight;
83+
width = (uint)originalImageWidth * width / OnnxModelScorer.ImageNetSettings.imageWidth;
84+
height = (uint)originalImageHeight * height / OnnxModelScorer.ImageNetSettings.imageHeight;
85+
86+
// Bounding Box Text
87+
string text = $"{box.Label} ({(box.Confidence * 100).ToString("0")}%)";
88+
89+
using (Graphics thumbnailGraphic = Graphics.FromImage(image))
90+
{
91+
thumbnailGraphic.CompositingQuality = CompositingQuality.HighQuality;
92+
thumbnailGraphic.SmoothingMode = SmoothingMode.HighQuality;
93+
thumbnailGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
94+
95+
// Define Text Options
96+
Font drawFont = new Font("Arial", 12, FontStyle.Bold);
97+
SizeF size = thumbnailGraphic.MeasureString(text, drawFont);
98+
SolidBrush fontBrush = new SolidBrush(Color.Black);
99+
Point atPoint = new Point((int)x, (int)y - (int)size.Height - 1);
100+
101+
// Define BoundingBox options
102+
Pen pen = new Pen(box.BoxColor, 3.2f);
103+
SolidBrush colorBrush = new SolidBrush(box.BoxColor);
104+
105+
// Draw text on image
106+
thumbnailGraphic.FillRectangle(colorBrush, (int)x, (int)(y - size.Height - 1), (int)size.Width, (int)size.Height);
107+
thumbnailGraphic.DrawString(text, drawFont, fontBrush, atPoint);
108+
109+
// Draw bounding box on image
110+
thumbnailGraphic.DrawRectangle(pen, x, y, width, height);
143111
}
144112
}
113+
114+
if (!Directory.Exists(outputImageLocation))
115+
{
116+
Directory.CreateDirectory(outputImageLocation);
117+
}
118+
119+
image.Save(Path.Combine(outputImageLocation, imageName));
145120
}
146121

122+
void LogDetectedObjects(string imageName, IList<YoloBoundingBox> boundingBoxes)
123+
{
124+
Console.WriteLine($".....The objects in the image {imageName} are detected as below....");
147125

126+
foreach (var box in boundingBoxes)
127+
{
128+
Console.WriteLine($"{box.Label} and its Confidence score: {box.Confidence}");
129+
}
148130

131+
Console.WriteLine("");
132+
}

samples/csharp/getting-started/Forecasting_BikeSharingDemand/BikeDemandForecasting/BikeDemandForecasting.csproj

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22

33
<PropertyGroup>
44
<OutputType>Exe</OutputType>
5-
<TargetFramework>net5</TargetFramework>
5+
<TargetFramework>net6.0</TargetFramework>
6+
<ImplicitUsings>enable</ImplicitUsings>
67
</PropertyGroup>
78

89
<ItemGroup>

0 commit comments

Comments
 (0)
0