WIL-PDL Reference ( .NET Framework ) 1.0.5-gpu
複数のモデルを並列実行するサンプルコード

複数のモデルを並列実行するサンプルコードです。

modelNamesimageSizes に指定されるモデルで iterNum 回推論を行うタスクをそれぞれ作成します。
作成したタスクたちを一斉に開始して並列実行し、すべてのタスクの完了を待ちます。


C# 版

  • ModelDirectory (L.27): モデルファイルたちが格納されたフォルダ ( 事前定義 )
  • ImageDirectory (L.28): 画像ファイルたちが格納されたフォルダ ( 事前定義 )
  • 引数 imageSizes: 画像サイズ
    • 対応する画像: test_img_{img_size}.PNGImageDirectory に格納されているものとします
    • ※ 多視点画像分類と多視点アノマリー検出では本来異なる複数枚の画像を入力しますが、ここでは簡単のため test_img_{img_size}.PNG を視点数と同じ枚数だけ複製した画像を入力します
  • 引数 modelNames: モデル名称
    • 対応するモデル: {model_name}_{img_size}.wilpdlModelDirectory に格納されているものとします
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using System.Threading.Tasks;
6using System.IO;
7using System.Diagnostics;
8using FVIL;
9using FVIL.Data;
10using FVIL.PDL;
11
12namespace SamplesCS
13{
14 partial class Program
15 {
16 static void UseMultiModel(List<String> modelNames, List<Int32> imageSizes, Int32 iterNum)
17 {
18 var has_license = Model.CheckLicense();
19 if (false == has_license) { throw new Exception("no license"); }
20
21 // それぞれのモデルと画像を準備してタスクのリストに格納
22 List<Task> tasks = new List<Task>();
23 foreach (var model_name in modelNames)
24 {
25 foreach (var img_size in imageSizes)
26 {
27 var model_path = Path.Combine(ModelDirectory, $"{model_name}_{img_size}.wilpdl");
28 var image_path = Path.Combine(ImageDirectory, $"test_img_{img_size}.PNG");
29
30 // 匿名関数でタスクを作成
31 var task = new Task(() =>
32 {
33 var str_id = $"{model_name}_{img_size}";
34 var sw = new Stopwatch();
35
36 // アノマリー検出のときのみ使用
37 var threshold = 10.0;
38 CFviImage anomaly_map = null;
39
40 // MVCNN のときのみ使用
41 List<CFviImage> images = null;
42
43 var contents = str_id + ", initializing...";
44 try
45 {
47 // 準備
49 Console.WriteLine(contents);
50
51 // モデルファイルの読込
52 Model model = new Model(model_path);
53
54 // 推論対象画像の読込
55 CFviImage image = new CFviImage(image_path);
56
57 // 推論対象画像の有効性確認
58 var is_valid_img = model.IsValidImage(image);
59 if (false == is_valid_img) { throw new Exception("invalid image"); }
60
61 // モデル種別に応じた準備
62 switch (model.ModelCategory)
63 {
64 case ModelCategory.Classification:
65 break;
66 case ModelCategory.AnomalyDetection:
67 anomaly_map = new CFviImage(image.HorzSize, image.VertSize, ImageType.UC8, 1);
68 break;
69 case ModelCategory.MultiViewCNN:
70 images = new List<CFviImage>();
71 for(var i_img=0; i_img < model.NumViews; i_img++)
72 {
73 images.Add(new CFviImage(image, false));
74 }
75 break;
76 case ModelCategory.MultiViewAD:
77 images = new List<CFviImage>();
78 for (var i_img = 0; i_img < model.NumViews; i_img++)
79 {
80 images.Add(new CFviImage(image, false));
81 }
82 break;
83 case ModelCategory.SemanticSegmentation:
84 case ModelCategory.PanopticSegmentation:
85 case ModelCategory.ObjectDetection:
86 break;
87 case ModelCategory.Unknown:
88 default: throw new NotImplementedException($"unknown model-category={model.ModelCategory}");
89 }
90
92 // ループ実行開始
94
95 contents = str_id + ", start";
96 Console.WriteLine(contents);
97 // 本体
98 for (var i = 0; i < iterNum; i++)
99 {
100 contents = str_id + $", {i:000}";
101 switch (model.ModelCategory)
102 {
103 case ModelCategory.Classification:// 画像分類
104 {
105 // 計測開始
106 sw.Start();
107
108 // 推論実行
109 var scores = model.PredictClassification(image);
110
111 // 計測終了
112 sw.Stop();
113
114 // 結果の文字列
115 contents = $"{(Double)sw.ElapsedTicks / (Double)System.Diagnostics.Stopwatch.Frequency * 1000}";
116 for (var i_score = 0; i_score < scores.Length; i_score++)
117 {
118 contents += $", {scores[i_score]}";
119 }
120 }
121 break;
122 case ModelCategory.AnomalyDetection:// アノマリー検出
123 {
124 // 計測開始
125 sw.Start();
126
127 // 推論実行
128 var tuple = model.PredictAnomaly(image, (float)threshold, anomaly_map);
129
130 // 計測終了
131 sw.Stop();
132
133 // 結果の文字列
134 contents = $"{(Double)sw.ElapsedTicks / (Double)System.Diagnostics.Stopwatch.Frequency * 1000}";
135 contents += ", " + (tuple.Item1 ? "anomaly" : "normal") + $", {tuple.Item2}";
136 }
137 break;
138 case ModelCategory.MultiViewCNN:// 多視点画像分類
139 {
140 // 計測開始
141 sw.Start();
142
143 // 推論実行
144 var scores = model.PredictMultiViewCNN(images);
145
146 // 計測終了
147 sw.Stop();
148
149 // 結果の文字列
150 //contents += $", {sw.ElapsedMilliseconds:000}";
151 contents = $"{(Double)sw.ElapsedTicks / (Double)System.Diagnostics.Stopwatch.Frequency * 1000}";
152 for (var i_score = 0; i_score < scores.Length; i_score++)
153 {
154 contents += $", {scores[i_score]}";
155 }
156 }
157 break;
158 case ModelCategory.MultiViewAD:// 多視点アノマリー検出
159 {
160 // 計測開始
161 sw.Start();
162
163 // 推論実行
164 var tuple = model.PredictMultiViewAD(images, (float)threshold, anomaly_map);
165
166 // 計測終了
167 sw.Stop();
168
169 // 結果の文字列
170 contents = $"{(Double)sw.ElapsedTicks / (Double)System.Diagnostics.Stopwatch.Frequency * 1000}";
171 contents += ", " + (tuple.Item1 ? "anomaly" : "normal") + $", {tuple.Item2}";
172 }
173 break;
174 case ModelCategory.SemanticSegmentation:// セマンティックセグメンテーション
175 {
176 // 計測開始
177 sw.Start();
178
179 // 推論実行
180 var segm_result_image = model.PredictSemanticSegmentation(image);
181
182 // 計測終了
183 sw.Stop();
184
185 // 結果の文字列
186 contents = $"{(Double)sw.ElapsedTicks / (Double)System.Diagnostics.Stopwatch.Frequency * 1000}";
187 }
188 break;
189 case ModelCategory.PanopticSegmentation:// パノプティックセグメンテーション
190 {
191 // 計測開始
192 sw.Start();
193
194 // 推論実行
195 var segm_result_image = model.PredictPanopticSegmentation(image);
196
197 // 計測終了
198 sw.Stop();
199
200 // 結果の文字列
201 contents = $"{(Double)sw.ElapsedTicks / (Double)System.Diagnostics.Stopwatch.Frequency * 1000}";
202 }
203 break;
204 case ModelCategory.ObjectDetection:// 物体検出
205 {
206 // 計測開始
207 sw.Start();
208
209 // 推論実行
210 var detections = model.PredictObjectDetection(image);
211
212 // 計測終了
213 sw.Stop();
214
215 // 結果の文字列
216 contents = $"{(Double)sw.ElapsedTicks / (Double)System.Diagnostics.Stopwatch.Frequency * 1000}";
217 contents += $", {detections.Count()}";
218 }
219 break;
220 case ModelCategory.Unknown:
221 default: throw new NotImplementedException($"unknown model-category={model.ModelCategory}");
222 }
223
224 Console.WriteLine(contents);
225 sw.Reset();
226 }
227 }
228 catch (Exception ex)
229 {
230 contents = str_id + ", error" + ex.Message;
231 Console.WriteLine(contents);
232 Console.WriteLine(ex.StackTrace);
233 return;
234 }
235
236 contents = str_id + ", finish";
237 Console.WriteLine(contents);
238 });
239
240 tasks.Add(task);
241 }
242 }
243
244 // 全てのタスクの開始
245 foreach(var task in tasks)
246 {
247 task.Start();
248 }
249 // 全てのタスクの終了待ち
250 Task.WaitAll(tasks.ToArray());
251 }
252 }
253}
推論するモデルを扱うクラス
Definition: PredictionCS.cs:244
ModelCategory ModelCategory
読み込んだモデルの種別
Definition: PredictionCS.cs:265
float[] PredictClassification(CFviImage targetImage)
推論の実行(画像分類)
Definition: PredictionCS.cs:986
Boolean IsValidImage(CFviImage targetImage)
推論画像の有効性の確認
Definition: PredictionCS.cs:669
static Boolean CheckLicense()
ライセンスを確認します。
Definition: PredictionCS.cs:419
IEnumerable< ObjectDetectionData > PredictObjectDetection(CFviImage targetImage)
推論の実行(物体検出)
Definition: PredictionCS.cs:1723
CFviImage PredictSemanticSegmentation(CFviImage targetImage)
推論の実行(セマンティックセグメンテーション)
Definition: PredictionCS.cs:1434
Tuple< Boolean, float > PredictMultiViewAD(IEnumerable< CFviImage > targetImages, float threshold)
推論の実行(多視点アノマリー検出)
Definition: PredictionCS.cs:1299
Int32 NumViews
読み込んだモデルが期待する視点数
Definition: PredictionCS.cs:308
Tuple< Boolean, float > PredictAnomaly(CFviImage targetImage, float threshold)
推論の実行(アノマリー検出)
Definition: PredictionCS.cs:1077
CFviImage PredictPanopticSegmentation(CFviImage targetImage)
推論の実行(パノプティックセグメンテーション)
Definition: PredictionCS.cs:1534
float[] PredictMultiViewCNN(IEnumerable< CFviImage > targetImages)
推論の実行(MVCNN)
Definition: PredictionCS.cs:1207
WIL-PDL モジュールの名前空間
Definition: PredictionCS.cs:21
ModelCategory
モデルの種別
Definition: PredictionCS.cs:32
FVILの最上位ネームスペース
Definition: PredictionCS.cs:16

VB 版

  • ModelDirectory (L.22): モデルファイルたちが格納されたフォルダ ( 事前定義 )
  • ImageDirectory (L.23): 画像ファイルたちが格納されたフォルダ ( 事前定義 )
  • 引数 imageSizes: 画像サイズ
    • 対応する画像: test_img_{img_size}.PNGImageDirectory に格納されているものとします
    • ※ 多視点画像分類と多視点アノマリー検出 では本来異なる複数枚の画像を入力しますが、ここでは簡単のため test_img_{img_size}.PNG を視点数と同じ枚数だけ複製した画像を入力します
  • 引数 modelNames: モデル名称
    • 対応するモデル: {model_name}_{img_size}.wilpdlModelDirectory に格納されているものとします
1Imports System
2Imports System.Collections.Generic
3Imports System.Linq
4Imports System.Threading.Tasks
5Imports System.IO
6Imports System.Diagnostics
7Imports FVIL
8Imports FVIL.Data
9Imports FVIL.PDL
10
11Namespace SamplesCS
12 Partial Class Program
13 Private Shared Sub UseMultiModel(modelNames As List(Of String), imageSizes As List(Of Integer), iterNum As Integer)
14 Dim has_license = Model.CheckLicense()
15 If False = has_license Then
16 Throw New Exception("no license")
17 End If
18
19 ' それぞれのモデルと画像を準備してタスクのリストに格納
20 Dim tasks As List(Of Task) = New List(Of Task)()
21 For Each model_name In modelNames
22 For Each img_size In imageSizes
23 Dim model_path = Path.Combine(Program.ModelDirectory, $"{model_name}_{img_size}.wilpdl")
24 Dim image_path = Path.Combine(Program.ImageDirectory, $"test_img_{img_size}.PNG")
25
26 ' 匿名関数でタスクを作成
27 Dim task = New Task(Sub()
28 Dim str_id = $"{model_name}_{img_size}"
29 Dim sw = New Stopwatch()
30
31 ' アノマリー検出のときのみ使用
32 Dim threshold = 10.0
33 Dim anomaly_map As CFviImage = Nothing
34
35 ' MVCNN のときのみ使用
36 Dim images As List(Of CFviImage) = Nothing
37
38 Dim contents = str_id & ", initializing..."
39 Try
40 '''''''''''
41 ' 準備
42 '''''''''''
43 Console.WriteLine(contents)
44
45 ' モデルファイルの読込
46 Dim model As Model = New Model(model_path)
47
48 ' 推論対象画像の読込
49 Dim image As CFviImage = New CFviImage(image_path)
50
51 ' 推論対象画像の有効性確認
52 Dim is_valid_img = model.IsValidImage(image)
53 If False = is_valid_img Then
54 Throw New Exception("invalid image")
55 End If
56
57 ' モデル種別に応じた準備
58 Select Case model.ModelCategory
59 Case ModelCategory.Classification
60 Case ModelCategory.AnomalyDetection
61 anomaly_map = New CFviImage(image.HorzSize, image.VertSize, ImageType.UC8, 1)
62 Case ModelCategory.MultiViewCNN
63 images = New List(Of CFviImage)()
64 For i_img = 0 To model.NumViews - 1
65 images.Add(New CFviImage(image, False))
66 Next
67 Case ModelCategory.MultiViewAD
68 images = New List(Of CFviImage)()
69 For i_img = 0 To model.NumViews - 1
70 images.Add(New CFviImage(image, False))
71 Next
72 Case ModelCategory.SemanticSegmentation, ModelCategory.PanopticSegmentation, ModelCategory.ObjectDetection
73 Case Else
74 Throw New NotImplementedException($"unknown model-category={model.ModelCategory}")
75 End Select
76
77 '''''''''''
78 ' ループ実行開始
79 '''''''''''
80
81 contents = str_id & ", start"
82 Console.WriteLine(contents)
83 ' 本体
84 For i = 0 To iterNum - 1
85 contents = str_id & $", {i:000}"
86 Select Case model.ModelCategory
87 Case ModelCategory.Classification ' 画像分類
88 ' 計測開始
89 sw.Start()
90
91 ' 推論実行
92 Dim scores = model.PredictClassification(image)
93
94 ' 計測終了
95 sw.Stop()
96
97 ' 結果の文字列
98 contents = $"{sw.ElapsedTicks / Stopwatch.Frequency * 1000}"
99 For i_score = 0 To scores.Length - 1
100 contents += $", {scores(i_score)}"
101 Next
102 Case ModelCategory.AnomalyDetection ' アノマリー検出
103 ' 計測開始
104 sw.Start()
105
106 ' 推論実行
107 Dim tuple = model.PredictAnomaly(image, threshold, anomaly_map)
108
109 ' 計測終了
110 sw.Stop()
111
112 ' 結果の文字列
113 contents = $"{sw.ElapsedTicks / Stopwatch.Frequency * 1000}"
114 contents += ", " & If(tuple.Item1, "anomaly", "normal") & $", {tuple.Item2}"
115 Case ModelCategory.MultiViewCNN ' 多視点画像分類
116 ' 計測開始
117 sw.Start()
118
119 ' 推論実行
120 Dim scores = model.PredictMultiViewCNN(images)
121
122 ' 計測終了
123 sw.Stop()
124
125 ' 結果の文字列
126 'contents += $", {sw.ElapsedMilliseconds:000}";
127 contents = $"{sw.ElapsedTicks / Stopwatch.Frequency * 1000}"
128 For i_score = 0 To scores.Length - 1
129 contents += $", {scores(i_score)}"
130 Next
131 Case ModelCategory.MultiViewAD ' 多視点アノマリー検出
132 ' 計測開始
133 sw.Start()
134
135 ' 推論実行
136 Dim tuple = model.PredictMultiViewAD(images, threshold, anomaly_map)
137
138 ' 計測終了
139 sw.Stop()
140
141 ' 結果の文字列
142 contents = $"{sw.ElapsedTicks / Stopwatch.Frequency * 1000}"
143 contents += ", " & If(tuple.Item1, "anomaly", "normal") & $", {tuple.Item2}"
144 Case ModelCategory.SemanticSegmentation ' セマンティックセグメンテーション
145 ' 計測開始
146 sw.Start()
147
148 ' 推論実行
149 Dim segm_result_image = model.PredictSemanticSegmentation(image)
150
151 ' 計測終了
152 sw.Stop()
153
154 ' 結果の文字列
155 contents = $"{sw.ElapsedTicks / Stopwatch.Frequency * 1000}"
156 Case ModelCategory.PanopticSegmentation ' パノプティックセグメンテーション
157 ' 計測開始
158 sw.Start()
159
160 ' 推論実行
161 Dim segm_result_image = model.PredictPanopticSegmentation(image)
162
163 ' 計測終了
164 sw.Stop()
165
166 ' 結果の文字列
167 contents = $"{sw.ElapsedTicks / Stopwatch.Frequency * 1000}"
168 Case ModelCategory.ObjectDetection ' 物体検出
169 ' 計測開始
170 sw.Start()
171
172 ' 推論実行
173 Dim detections = model.PredictObjectDetection(image)
174
175 ' 計測終了
176 sw.Stop()
177
178 ' 結果の文字列
179 contents = $"{sw.ElapsedTicks / Stopwatch.Frequency * 1000}"
180 contents += $", {detections.Count()}"
181 Case Else
182 Throw New NotImplementedException($"unknown model-category={model.ModelCategory}")
183 End Select
184
185 Console.WriteLine(contents)
186 sw.Reset()
187 Next
188 Catch ex As Exception
189 contents = str_id & ", error" & ex.Message
190 Console.WriteLine(contents)
191 Console.WriteLine(ex.StackTrace)
192 Return
193 End Try
194
195 contents = str_id & ", finish"
196 Console.WriteLine(contents)
197 End Sub)
198
199 tasks.Add(task)
200 Next
201 Next
202
203 ' 全てのタスクの開始
204 For Each task In tasks
205 task.Start()
206 Next
207 ' 全てのタスクの終了待ち
208 Call Task.WaitAll(tasks.ToArray())
209 End Sub
210 End Class
211End Namespace

Documentation copyright © 2025 TOKYO ELECTRON DEVICE LIMITED https://www.teldevice.co.jp/
Generated on Thu Jan 23 2025 16:11:33 for WIL-PDL Reference ( .NET Framework ) 1.0.5-gpu by Doxygen 1.9.5.