WIL-PDL Reference ( .NET Framework ) 1.0.1
ベンチマークを計測するサンプルコード

ベンチマークを計測するサンプルコードです。
iterNum で繰り返し回数を指定します。


C# 版

  • 画像分類の場合: L.14 BenchMark()
  • アノマリー検出の場合: L.14 BenchMark()
  • MVCNN の場合: L.130- BenchMarkMVCNN()
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using System.Threading.Tasks;
6using FVIL;
7using FVIL.Data;
8using FVIL.PDL;
9
10namespace SamplesCS
11{
12 partial class Program
13 {
14 static void BenchMark(String modelPath, String imagePath, UInt32 iterNum)
15 {
16 // 閾値は任意、必要であれば引数としても良い
17 const Double threshold = 10.0;
18 // アノマリー検出での異常度マップ画像の型 ( UC8 または F32 )
19 const ImageType anomaly_map_image_type = ImageType.UC8;
20
21 // 計測回数のエラーチェック
22 if (0 >= iterNum)
23 {
24 Console.WriteLine("iterNum must be positive ( >0 )");
25 return;
26 }
27
28 try
29 {
30 var has_license = Model.CheckLicense();
31 if (false == has_license) { throw new Exception("no license"); }
32
33 // モデルファイルの読込を含むコンストラクタ ( インスタンスを作成して LoadModel() をする場合と同等 )
34 Model model = new Model(modelPath);
35
36 // 推論対象画像の読込
37 CFviImage image = new CFviImage(imagePath);
38
39 // 推論対象画像の有効性確認
40 var is_valid_img = model.IsValidImage(image);
41 if (false == is_valid_img) { throw new Exception("invalid image"); }
42
43 // アノマリー検出での異常度マップ画像
44 CFviImage anomaly_map = new CFviImage(image.HorzSize, image.VertSize, anomaly_map_image_type, 1);
45
46 // 計測用のストップウォッチ
47 System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
48
49 // 計測結果のリスト
50 long[] msecs = new long[iterNum];
51
52 var contents = "msec, score0,...";
53 Console.WriteLine("msec, score0,...");
54 for (var i = 0; i < iterNum; i++)
55 {
56 switch (model.ModelCategory)
57 {
58 case ModelCategory.Classification:// 画像分類
59 {
60 // 計測開始
61 sw.Start();
62
63 // 推論実行
64 var scores = model.PredictClassification(image);
65
66 // 計測終了
67 sw.Stop();
68
69 // 結果の文字列
70 contents = $"{(Double)sw.ElapsedTicks / (Double)System.Diagnostics.Stopwatch.Frequency * 1000}";
71 for (var i_score = 0; i_score < scores.Length; i_score++)
72 {
73 contents += $", {scores[i_score]}";
74 }
75 }
76 break;
77 case ModelCategory.AnomalyDetection:// アノマリー検出
78 {
79 // 計測開始
80 sw.Start();
81
82 // 推論実行
83 var tuple = model.PredictAnomaly(image, (float)threshold, anomaly_map);
84
85 // 計測終了
86 sw.Stop();
87
88 // 結果の文字列
89 //contents = $"{sw.ElapsedMilliseconds:000}";
90 contents = $"{(Double)sw.ElapsedTicks / (Double)System.Diagnostics.Stopwatch.Frequency * 1000}";
91 contents += ", " + (tuple.Item1 ? "anomaly" : "normal") + $", {tuple.Item2}";
92 }
93 break;
94 case ModelCategory.Unknown:
95 case ModelCategory.MultiViewCNN:
96 default: throw new NotImplementedException($"unmatch model-category={model.ModelCategory}");
97 }
98
99 // リストへ格納
100 msecs[i] = sw.ElapsedMilliseconds;
101
102 Console.WriteLine(contents);
103
104 // ファイルに保存したいとき
105 // - "result.csv" は任意のパスを設定
106 // - 上記の contents 生成に改行を追加
107 //System.IO.File.AppendAllText("result.csv", contents + Environment.NewLine);
108
109 // 次の計測のためのリセット
110 sw.Reset();
111 }
112
113 // 全体の結果
114 Console.WriteLine($"Ave: {msecs.Average():.00}");
115 Console.WriteLine($"Min: {msecs.Min():.00}");
116 Console.WriteLine($"Max: {msecs.Max():.00}");
117 }
118 catch (CFviException ex)
119 {
120 Console.WriteLine($"ErrorCode={ex.ErrorCode}, Message={ex.Message}");
121 Console.WriteLine(ex.StackTrace);
122 }
123 catch (Exception ex)
124 {
125 Console.WriteLine($"Message={ex.Message}");
126 Console.WriteLine(ex.StackTrace);
127 }
128 }
129
130 static void BenchMarkMVCNN(String modelPath, String imageFolder, UInt32 iterNum)
131 {
132 // 計測回数のエラーチェック
133 if (0 >= iterNum)
134 {
135 Console.WriteLine("iterNum must be positive ( >0 )");
136 return;
137 }
138
139 try
140 {
141 var has_license = Model.CheckLicense();
142 if (false == has_license) { throw new Exception("no license"); }
143
144 // モデルファイルの読込を含むコンストラクタ ( インスタンスを作成して LoadModel() をする場合と同等 )
145 Model model = new Model(modelPath);
146
147 // モデル種別のエラーチェック
148 switch (model.ModelCategory)
149 {
150 case ModelCategory.MultiViewCNN:
151 break;
152 case ModelCategory.Unknown:
153 case ModelCategory.Classification:
154 case ModelCategory.AnomalyDetection:
155 default: throw new NotImplementedException($"unmatch model-category={model.ModelCategory}");
156 }
157
158 // 推論対象画像の読込と有効性の確認
159 List<CFviImage> target_images = new List<CFviImage>();
160 for (var i_img = 0; i_img < model.NumViews; i_img++)
161 {
162 // imageFolder フォルダ内に、0-index の通し番号の画像が保存されていることを想定
163 var img_path = System.IO.Path.Combine(imageFolder, String.Format("{0}.bmp", i_img));
164 var image = new CFviImage(img_path);
165
166 // 推論対象画像の有効性確認
167 var is_valid_img = model.IsValidImage(image);
168 if (false == is_valid_img) { throw new Exception("invalid image"); }
169
170 // 推論対象画像のリストに追加
171 target_images.Add(image);
172 }
173
174 // 計測用のストップウォッチ
175 System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
176
177 // 計測結果のリスト
178 long[] msecs = new long[iterNum];
179
180 var contents = "msec, score0,...";
181 Console.WriteLine("msec, score0,...");
182 for (var i = 0; i < iterNum; i++)
183 {
184 // 計測開始
185 sw.Start();
186
187 // 推論実行
188 var scores = model.PredictMultiViewCNN(target_images);
189
190 // 計測終了
191 sw.Stop();
192
193 // 結果の文字列
194 //contents = $"{sw.ElapsedMilliseconds:000}";
195 contents = $"{(Double)sw.ElapsedTicks / (Double)System.Diagnostics.Stopwatch.Frequency * 1000}";
196 for (var i_score = 0; i_score < scores.Length; i_score++)
197 {
198 contents += $", {scores[i_score]}";
199 }
200
201 // リストへ格納
202 msecs[i] = sw.ElapsedMilliseconds;
203
204 Console.WriteLine(contents);
205
206 // ファイルに保存したいとき
207 // - "result.csv" は任意のパスを設定
208 // - 上記の contents 生成に改行を追加
209 //System.IO.File.AppendAllText("result.csv", contents + Environment.NewLine);
210
211 // 次の計測のためのリセット
212 sw.Reset();
213 }
214
215 // 全体の結果
216 Console.WriteLine($"Ave: {msecs.Average():.00}");
217 Console.WriteLine($"Min: {msecs.Min():.00}");
218 Console.WriteLine($"Max: {msecs.Max():.00}");
219 }
220 catch (CFviException ex)
221 {
222 Console.WriteLine($"ErrorCode={ex.ErrorCode}, Message={ex.Message}");
223 Console.WriteLine(ex.StackTrace);
224 }
225 catch (Exception ex)
226 {
227 Console.WriteLine($"Message={ex.Message}");
228 Console.WriteLine(ex.StackTrace);
229 }
230 }
231 }
232}
推論するモデルを扱うクラス
Definition: PredictionCS.cs:101
ModelCategory ModelCategory
読み込んだモデルの種別
Definition: PredictionCS.cs:122
float[] PredictClassification(CFviImage targetImage)
推論の実行(画像分類)
Definition: PredictionCS.cs:599
Boolean IsValidImage(CFviImage targetImage)
推論画像の有効性の確認
Definition: PredictionCS.cs:425
static Boolean CheckLicense()
ライセンスを確認します。
Definition: PredictionCS.cs:241
Int32 NumViews
読み込んだモデルが期待する視点数
Definition: PredictionCS.cs:151
Tuple< Boolean, float > PredictAnomaly(CFviImage targetImage, float threshold)
推論の実行(アノマリー検出)
Definition: PredictionCS.cs:680
float[] PredictMultiViewCNN(IEnumerable< CFviImage > targetImages)
推論の実行(MVCNN)
Definition: PredictionCS.cs:829
WIL-PDL モジュールの名前空間
Definition: PredictionCS.cs:20
ModelCategory
モデルの種別
Definition: PredictionCS.cs:30
FVILの最上位ネームスペース
Definition: PredictionCS.cs:15

VB 版

  • 画像分類の場合: L.11 BenchMark()
  • アノマリー検出の場合: L.11 BenchMark()
  • MVCNN の場合: L.114- BenchMarkMVCNN()
1Imports System
2Imports System.Collections.Generic
3Imports System.Linq
4Imports System.IO
5Imports FVIL
6Imports FVIL.Data
7Imports FVIL.PDL
8
9Namespace SamplesCS
10 Partial Class Program
11 Private Shared Sub BenchMark(ByVal modelPath As String, ByVal imagePath As String, ByVal iterNum As UInteger)
12 ' 閾値は任意、必要であれば引数としても良い
13 Const threshold = 10.0
14 ' アノマリー検出での異常度マップ画像の型 ( UC8 または F32 )
15 Const anomaly_map_image_type = ImageType.UC8
16
17 ' 計測回数のエラーチェック
18 If 0 >= iterNum Then
19 Console.WriteLine("iterNum must be positive ( >0 )")
20 Return
21 End If
22
23 Try
24 Dim has_license = PDL.Model.CheckLicense()
25 If False = has_license Then
26 Throw New Exception("no license")
27 End If
28
29 ' モデルファイルの読込を含むコンストラクタ ( インスタンスを作成して LoadModel() をする場合と同等 )
30 Dim model As Model = New Model(modelPath)
31
32 ' 推論対象画像の読込
33 Dim image As CFviImage = New CFviImage(imagePath)
34
35 ' 推論対象画像の有効性確認
36 Dim is_valid_img = model.IsValidImage(image)
37 If False = is_valid_img Then
38 Throw New Exception("invalid image")
39 End If
40
41 ' アノマリー検出での異常度マップ画像
42 Dim anomaly_map As CFviImage = New CFviImage(image.HorzSize, image.VertSize, anomaly_map_image_type, 1)
43
44 ' 計測用のストップウォッチ
45 Dim sw As Stopwatch = New Stopwatch()
46
47 ' 計測結果のリスト
48 Dim msecs = New Long(iterNum - 1) {}
49
50 Dim contents = "msec, score0,..."
51 Console.WriteLine("msec, score0,...")
52 For i = 0 To iterNum - 1
53 Select Case model.ModelCategory
54 Case ModelCategory.Classification ' 画像分類
55 ' 計測開始
56 sw.Start()
57
58 ' 推論実行
59 Dim scores = model.PredictClassification(image)
60
61 ' 計測終了
62 sw.Stop()
63
64 ' 結果の文字列
65 contents = $"{sw.ElapsedTicks / Stopwatch.Frequency * 1000}"
66 For i_score = 0 To scores.Length - 1
67 contents += $", {scores(i_score)}"
68 Next
69 Case ModelCategory.AnomalyDetection ' アノマリー検出
70 ' 計測開始
71 sw.Start()
72
73 ' 推論実行
74 Dim tuple = model.PredictAnomaly(image, threshold, anomaly_map)
75
76 ' 計測終了
77 sw.Stop()
78
79 ' 結果の文字列
80 'contents = $"{sw.ElapsedMilliseconds:000}";
81 contents = $"{sw.ElapsedTicks / Stopwatch.Frequency * 1000}"
82 contents += ", " & If(tuple.Item1, "anomaly", "normal") & $", {tuple.Item2}"
83 Case Else
84 Throw New NotImplementedException($"unmatch model-category={model.ModelCategory}")
85 End Select
86
87 ' リストへ格納
88 msecs(i) = sw.ElapsedMilliseconds
89
90 Console.WriteLine(contents)
91
92 ' ファイルに保存したいとき
93 ' - "result.csv" は任意のパスを設定
94 ' - 上記の contents 生成に改行を追加
95 'System.IO.File.AppendAllText("result.csv", contents + Environment.NewLine);
96
97 ' 次の計測のためのリセット
98 sw.Reset()
99 Next
100
101 ' 全体の結果
102 Console.WriteLine($"Ave: {msecs.Average():.00}")
103 Console.WriteLine($"Min: {msecs.Min():.00}")
104 Console.WriteLine($"Max: {msecs.Max():.00}")
105 Catch ex As CFviException
106 Console.WriteLine($"ErrorCode={ex.ErrorCode}, Message={ex.Message}")
107 Console.WriteLine(ex.StackTrace)
108 Catch ex As Exception
109 Console.WriteLine($"Message={ex.Message}")
110 Console.WriteLine(ex.StackTrace)
111 End Try
112 End Sub
113
114 Private Shared Sub BenchMarkMVCNN(ByVal modelPath As String, ByVal imageFolder As String, ByVal iterNum As UInteger)
115 ' 計測回数のエラーチェック
116 If 0 >= iterNum Then
117 Console.WriteLine("iterNum must be positive ( >0 )")
118 Return
119 End If
120
121 Try
122 Dim has_license = PDL.Model.CheckLicense()
123 If False = has_license Then
124 Throw New Exception("no license")
125 End If
126
127 ' モデルファイルの読込を含むコンストラクタ ( インスタンスを作成して LoadModel() をする場合と同等 )
128 Dim model As Model = New Model(modelPath)
129
130 ' モデル種別のエラーチェック
131 Select Case model.ModelCategory
132 Case ModelCategory.MultiViewCNN
133 Case Else
134 Throw New NotImplementedException($"unmatch model-category={model.ModelCategory}")
135 End Select
136
137 ' 推論対象画像の読込と有効性の確認
138 Dim target_images As List(Of CFviImage) = New List(Of CFviImage)()
139 For i_img = 0 To model.NumViews - 1
140 ' imageFolder フォルダ内に、0-index の通し番号の画像が保存されていることを想定
141 Dim img_path = Path.Combine(imageFolder, String.Format("{0}.bmp", i_img))
142 Dim image = New CFviImage(img_path)
143
144 ' 推論対象画像の有効性確認
145 Dim is_valid_img = model.IsValidImage(image)
146 If False = is_valid_img Then
147 Throw New Exception("invalid image")
148 End If
149
150 ' 推論対象画像のリストに追加
151 target_images.Add(image)
152 Next
153
154 ' 計測用のストップウォッチ
155 Dim sw As Stopwatch = New Stopwatch()
156
157 ' 計測結果のリスト
158 Dim msecs = New Long(iterNum - 1) {}
159
160 Dim contents = "msec, score0,..."
161 Console.WriteLine("msec, score0,...")
162 For i = 0 To iterNum - 1
163 ' 計測開始
164 sw.Start()
165
166 ' 推論実行
167 Dim scores = model.PredictMultiViewCNN(target_images)
168
169 ' 計測終了
170 sw.Stop()
171
172 ' 結果の文字列
173 'contents = $"{sw.ElapsedMilliseconds:000}";
174 contents = $"{sw.ElapsedTicks / Stopwatch.Frequency * 1000}"
175 For i_score = 0 To scores.Length - 1
176 contents += $", {scores(i_score)}"
177 Next
178
179 ' リストへ格納
180 msecs(i) = sw.ElapsedMilliseconds
181
182 Console.WriteLine(contents)
183
184 ' ファイルに保存したいとき
185 ' - "result.csv" は任意のパスを設定
186 ' - 上記の contents 生成に改行を追加
187 'System.IO.File.AppendAllText("result.csv", contents + Environment.NewLine);
188
189 ' 次の計測のためのリセット
190 sw.Reset()
191 Next
192
193 ' 全体の結果
194 Console.WriteLine($"Ave: {msecs.Average():.00}")
195 Console.WriteLine($"Min: {msecs.Min():.00}")
196 Console.WriteLine($"Max: {msecs.Max():.00}")
197 Catch ex As CFviException
198 Console.WriteLine($"ErrorCode={ex.ErrorCode}, Message={ex.Message}")
199 Console.WriteLine(ex.StackTrace)
200 Catch ex As Exception
201 Console.WriteLine($"Message={ex.Message}")
202 Console.WriteLine(ex.StackTrace)
203 End Try
204 End Sub
205 End Class
206End Namespace

Documentation copyright © 2008 FAST Corporation. https://www.fast-corp.co.jp/
Generated on Sun Jan 15 2023 13:40:43 for WIL-PDL Reference ( .NET Framework ) 1.0.1 by Doxygen 1.9.5.