├── .gitattributes
├── .gitignore
├── DeepLearning_MNIST.sln
├── DeepLearning_MNIST
├── App.config
├── ClassifierParamsSetForm.Designer.cs
├── ClassifierParamsSetForm.cs
├── ClassifierParamsSetForm.resx
├── DeepLearning_MNIST.csproj
├── Form1.Designer.cs
├── Form1.cs
├── Form1.resx
├── HalconTools.cs
├── MNIST.cs
├── Preprocess.cs
├── Program.cs
├── Properties
│ ├── AssemblyInfo.cs
│ ├── Resources.Designer.cs
│ ├── Resources.resx
│ ├── Settings.Designer.cs
│ └── Settings.settings
├── Readme.txt
├── Test.cs
└── Train.cs
├── Readme.txt
├── mnist_images.rar
├── screenshot (1).png
├── screenshot (2).png
└── screenshot (3).png
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Build results
17 | [Dd]ebug/
18 | [Dd]ebugPublic/
19 | [Rr]elease/
20 | [Rr]eleases/
21 | x64/
22 | x86/
23 | [Aa][Rr][Mm]/
24 | [Aa][Rr][Mm]64/
25 | bld/
26 | [Bb]in/
27 | [Oo]bj/
28 | [Ll]og/
29 |
30 | # Visual Studio 2015/2017 cache/options directory
31 | .vs/
32 | # Uncomment if you have tasks that create the project's static files in wwwroot
33 | #wwwroot/
34 |
35 | # Visual Studio 2017 auto generated files
36 | Generated\ Files/
37 |
38 | # MSTest test Results
39 | [Tt]est[Rr]esult*/
40 | [Bb]uild[Ll]og.*
41 |
42 | # NUNIT
43 | *.VisualState.xml
44 | TestResult.xml
45 |
46 | # Build Results of an ATL Project
47 | [Dd]ebugPS/
48 | [Rr]eleasePS/
49 | dlldata.c
50 |
51 | # Benchmark Results
52 | BenchmarkDotNet.Artifacts/
53 |
54 | # .NET Core
55 | project.lock.json
56 | project.fragment.lock.json
57 | artifacts/
58 |
59 | # StyleCop
60 | StyleCopReport.xml
61 |
62 | # Files built by Visual Studio
63 | *_i.c
64 | *_p.c
65 | *_h.h
66 | *.ilk
67 | *.meta
68 | *.obj
69 | *.iobj
70 | *.pch
71 | *.pdb
72 | *.ipdb
73 | *.pgc
74 | *.pgd
75 | *.rsp
76 | *.sbr
77 | *.tlb
78 | *.tli
79 | *.tlh
80 | *.tmp
81 | *.tmp_proj
82 | *_wpftmp.csproj
83 | *.log
84 | *.vspscc
85 | *.vssscc
86 | .builds
87 | *.pidb
88 | *.svclog
89 | *.scc
90 |
91 | # Chutzpah Test files
92 | _Chutzpah*
93 |
94 | # Visual C++ cache files
95 | ipch/
96 | *.aps
97 | *.ncb
98 | *.opendb
99 | *.opensdf
100 | *.sdf
101 | *.cachefile
102 | *.VC.db
103 | *.VC.VC.opendb
104 |
105 | # Visual Studio profiler
106 | *.psess
107 | *.vsp
108 | *.vspx
109 | *.sap
110 |
111 | # Visual Studio Trace Files
112 | *.e2e
113 |
114 | # TFS 2012 Local Workspace
115 | $tf/
116 |
117 | # Guidance Automation Toolkit
118 | *.gpState
119 |
120 | # ReSharper is a .NET coding add-in
121 | _ReSharper*/
122 | *.[Rr]e[Ss]harper
123 | *.DotSettings.user
124 |
125 | # JustCode is a .NET coding add-in
126 | .JustCode
127 |
128 | # TeamCity is a build add-in
129 | _TeamCity*
130 |
131 | # DotCover is a Code Coverage Tool
132 | *.dotCover
133 |
134 | # AxoCover is a Code Coverage Tool
135 | .axoCover/*
136 | !.axoCover/settings.json
137 |
138 | # Visual Studio code coverage results
139 | *.coverage
140 | *.coveragexml
141 |
142 | # NCrunch
143 | _NCrunch_*
144 | .*crunch*.local.xml
145 | nCrunchTemp_*
146 |
147 | # MightyMoose
148 | *.mm.*
149 | AutoTest.Net/
150 |
151 | # Web workbench (sass)
152 | .sass-cache/
153 |
154 | # Installshield output folder
155 | [Ee]xpress/
156 |
157 | # DocProject is a documentation generator add-in
158 | DocProject/buildhelp/
159 | DocProject/Help/*.HxT
160 | DocProject/Help/*.HxC
161 | DocProject/Help/*.hhc
162 | DocProject/Help/*.hhk
163 | DocProject/Help/*.hhp
164 | DocProject/Help/Html2
165 | DocProject/Help/html
166 |
167 | # Click-Once directory
168 | publish/
169 |
170 | # Publish Web Output
171 | *.[Pp]ublish.xml
172 | *.azurePubxml
173 | # Note: Comment the next line if you want to checkin your web deploy settings,
174 | # but database connection strings (with potential passwords) will be unencrypted
175 | *.pubxml
176 | *.publishproj
177 |
178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
179 | # checkin your Azure Web App publish settings, but sensitive information contained
180 | # in these scripts will be unencrypted
181 | PublishScripts/
182 |
183 | # NuGet Packages
184 | *.nupkg
185 | # The packages folder can be ignored because of Package Restore
186 | **/[Pp]ackages/*
187 | # except build/, which is used as an MSBuild target.
188 | !**/[Pp]ackages/build/
189 | # Uncomment if necessary however generally it will be regenerated when needed
190 | #!**/[Pp]ackages/repositories.config
191 | # NuGet v3's project.json files produces more ignorable files
192 | *.nuget.props
193 | *.nuget.targets
194 |
195 | # Microsoft Azure Build Output
196 | csx/
197 | *.build.csdef
198 |
199 | # Microsoft Azure Emulator
200 | ecf/
201 | rcf/
202 |
203 | # Windows Store app package directories and files
204 | AppPackages/
205 | BundleArtifacts/
206 | Package.StoreAssociation.xml
207 | _pkginfo.txt
208 | *.appx
209 |
210 | # Visual Studio cache files
211 | # files ending in .cache can be ignored
212 | *.[Cc]ache
213 | # but keep track of directories ending in .cache
214 | !?*.[Cc]ache/
215 |
216 | # Others
217 | ClientBin/
218 | ~$*
219 | *~
220 | *.dbmdl
221 | *.dbproj.schemaview
222 | *.jfm
223 | *.pfx
224 | *.publishsettings
225 | orleans.codegen.cs
226 |
227 | # Including strong name files can present a security risk
228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
229 | #*.snk
230 |
231 | # Since there are multiple workflows, uncomment next line to ignore bower_components
232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
233 | #bower_components/
234 |
235 | # RIA/Silverlight projects
236 | Generated_Code/
237 |
238 | # Backup & report files from converting an old project file
239 | # to a newer Visual Studio version. Backup files are not needed,
240 | # because we have git ;-)
241 | _UpgradeReport_Files/
242 | Backup*/
243 | UpgradeLog*.XML
244 | UpgradeLog*.htm
245 | ServiceFabricBackup/
246 | *.rptproj.bak
247 |
248 | # SQL Server files
249 | *.mdf
250 | *.ldf
251 | *.ndf
252 |
253 | # Business Intelligence projects
254 | *.rdl.data
255 | *.bim.layout
256 | *.bim_*.settings
257 | *.rptproj.rsuser
258 | *- Backup*.rdl
259 |
260 | # Microsoft Fakes
261 | FakesAssemblies/
262 |
263 | # GhostDoc plugin setting file
264 | *.GhostDoc.xml
265 |
266 | # Node.js Tools for Visual Studio
267 | .ntvs_analysis.dat
268 | node_modules/
269 |
270 | # Visual Studio 6 build log
271 | *.plg
272 |
273 | # Visual Studio 6 workspace options file
274 | *.opt
275 |
276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
277 | *.vbw
278 |
279 | # Visual Studio LightSwitch build output
280 | **/*.HTMLClient/GeneratedArtifacts
281 | **/*.DesktopClient/GeneratedArtifacts
282 | **/*.DesktopClient/ModelManifest.xml
283 | **/*.Server/GeneratedArtifacts
284 | **/*.Server/ModelManifest.xml
285 | _Pvt_Extensions
286 |
287 | # Paket dependency manager
288 | .paket/paket.exe
289 | paket-files/
290 |
291 | # FAKE - F# Make
292 | .fake/
293 |
294 | # JetBrains Rider
295 | .idea/
296 | *.sln.iml
297 |
298 | # CodeRush personal settings
299 | .cr/personal
300 |
301 | # Python Tools for Visual Studio (PTVS)
302 | __pycache__/
303 | *.pyc
304 |
305 | # Cake - Uncomment if you are using it
306 | # tools/**
307 | # !tools/packages.config
308 |
309 | # Tabs Studio
310 | *.tss
311 |
312 | # Telerik's JustMock configuration file
313 | *.jmconfig
314 |
315 | # BizTalk build output
316 | *.btp.cs
317 | *.btm.cs
318 | *.odx.cs
319 | *.xsd.cs
320 |
321 | # OpenCover UI analysis results
322 | OpenCover/
323 |
324 | # Azure Stream Analytics local run output
325 | ASALocalRun/
326 |
327 | # MSBuild Binary and Structured Log
328 | *.binlog
329 |
330 | # NVidia Nsight GPU debugger configuration file
331 | *.nvuser
332 |
333 | # MFractors (Xamarin productivity tool) working folder
334 | .mfractor/
335 |
336 | # Local History for Visual Studio
337 | .localhistory/
338 |
339 | # BeatPulse healthcheck temp database
340 | healthchecksdb
--------------------------------------------------------------------------------
/DeepLearning_MNIST.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 14
4 | VisualStudioVersion = 14.0.25420.1
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DeepLearning_MNIST", "DeepLearning_MNIST\DeepLearning_MNIST.csproj", "{86425A08-EFBA-44AF-AA45-C5F71AFFB21B}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {86425A08-EFBA-44AF-AA45-C5F71AFFB21B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {86425A08-EFBA-44AF-AA45-C5F71AFFB21B}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {86425A08-EFBA-44AF-AA45-C5F71AFFB21B}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {86425A08-EFBA-44AF-AA45-C5F71AFFB21B}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | EndGlobal
23 |
--------------------------------------------------------------------------------
/DeepLearning_MNIST/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/DeepLearning_MNIST/ClassifierParamsSetForm.Designer.cs:
--------------------------------------------------------------------------------
1 | namespace DeepLearning_MNIST
2 | {
3 | partial class ClassifierParamsSetForm
4 | {
5 | ///
6 | /// Required designer variable.
7 | ///
8 | private System.ComponentModel.IContainer components = null;
9 |
10 | ///
11 | /// Clean up any resources being used.
12 | ///
13 | /// true if managed resources should be disposed; otherwise, false.
14 | protected override void Dispose(bool disposing)
15 | {
16 | if (disposing && (components != null))
17 | {
18 | components.Dispose();
19 | }
20 | base.Dispose(disposing);
21 | }
22 |
23 | #region Windows Form Designer generated code
24 |
25 | ///
26 | /// Required method for Designer support - do not modify
27 | /// the contents of this method with the code editor.
28 | ///
29 | private void InitializeComponent()
30 | {
31 | System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ClassifierParamsSetForm));
32 | this.groupBox1 = new System.Windows.Forms.GroupBox();
33 | this.numericUpDownValidationPercent = new System.Windows.Forms.NumericUpDown();
34 | this.label8 = new System.Windows.Forms.Label();
35 | this.textBoxLearningRateStepRatio = new System.Windows.Forms.TextBox();
36 | this.textBoxInitialLearningRate = new System.Windows.Forms.TextBox();
37 | this.numericUpDownTrainingPercent = new System.Windows.Forms.NumericUpDown();
38 | this.numericUpDownNumEpochs = new System.Windows.Forms.NumericUpDown();
39 | this.numericUpDownBatchSize = new System.Windows.Forms.NumericUpDown();
40 | this.numericUpDownLearningRateSENE = new System.Windows.Forms.NumericUpDown();
41 | this.label7 = new System.Windows.Forms.Label();
42 | this.label5 = new System.Windows.Forms.Label();
43 | this.label4 = new System.Windows.Forms.Label();
44 | this.label3 = new System.Windows.Forms.Label();
45 | this.label2 = new System.Windows.Forms.Label();
46 | this.label1 = new System.Windows.Forms.Label();
47 | this.btnConfirm = new System.Windows.Forms.Button();
48 | this.btnCancel = new System.Windows.Forms.Button();
49 | this.groupBox1.SuspendLayout();
50 | ((System.ComponentModel.ISupportInitialize)(this.numericUpDownValidationPercent)).BeginInit();
51 | ((System.ComponentModel.ISupportInitialize)(this.numericUpDownTrainingPercent)).BeginInit();
52 | ((System.ComponentModel.ISupportInitialize)(this.numericUpDownNumEpochs)).BeginInit();
53 | ((System.ComponentModel.ISupportInitialize)(this.numericUpDownBatchSize)).BeginInit();
54 | ((System.ComponentModel.ISupportInitialize)(this.numericUpDownLearningRateSENE)).BeginInit();
55 | this.SuspendLayout();
56 | //
57 | // groupBox1
58 | //
59 | this.groupBox1.Controls.Add(this.numericUpDownValidationPercent);
60 | this.groupBox1.Controls.Add(this.label8);
61 | this.groupBox1.Controls.Add(this.textBoxLearningRateStepRatio);
62 | this.groupBox1.Controls.Add(this.textBoxInitialLearningRate);
63 | this.groupBox1.Controls.Add(this.numericUpDownTrainingPercent);
64 | this.groupBox1.Controls.Add(this.numericUpDownNumEpochs);
65 | this.groupBox1.Controls.Add(this.numericUpDownBatchSize);
66 | this.groupBox1.Controls.Add(this.numericUpDownLearningRateSENE);
67 | this.groupBox1.Controls.Add(this.label7);
68 | this.groupBox1.Controls.Add(this.label5);
69 | this.groupBox1.Controls.Add(this.label4);
70 | this.groupBox1.Controls.Add(this.label3);
71 | this.groupBox1.Controls.Add(this.label2);
72 | this.groupBox1.Controls.Add(this.label1);
73 | this.groupBox1.Location = new System.Drawing.Point(12, 12);
74 | this.groupBox1.Name = "groupBox1";
75 | this.groupBox1.Size = new System.Drawing.Size(451, 301);
76 | this.groupBox1.TabIndex = 0;
77 | this.groupBox1.TabStop = false;
78 | this.groupBox1.Text = "训练参数设置";
79 | //
80 | // numericUpDownValidationPercent
81 | //
82 | this.numericUpDownValidationPercent.Location = new System.Drawing.Point(278, 258);
83 | this.numericUpDownValidationPercent.Name = "numericUpDownValidationPercent";
84 | this.numericUpDownValidationPercent.Size = new System.Drawing.Size(154, 25);
85 | this.numericUpDownValidationPercent.TabIndex = 18;
86 | this.numericUpDownValidationPercent.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
87 | this.numericUpDownValidationPercent.Value = new decimal(new int[] {
88 | 20,
89 | 0,
90 | 0,
91 | 0});
92 | this.numericUpDownValidationPercent.ValueChanged += new System.EventHandler(this.numericUpDownValidationPercent_ValueChanged);
93 | //
94 | // label8
95 | //
96 | this.label8.AutoSize = true;
97 | this.label8.Location = new System.Drawing.Point(111, 263);
98 | this.label8.Name = "label8";
99 | this.label8.Size = new System.Drawing.Size(151, 15);
100 | this.label8.TabIndex = 17;
101 | this.label8.Text = "ValidationPercent:";
102 | //
103 | // textBoxLearningRateStepRatio
104 | //
105 | this.textBoxLearningRateStepRatio.Location = new System.Drawing.Point(278, 147);
106 | this.textBoxLearningRateStepRatio.Name = "textBoxLearningRateStepRatio";
107 | this.textBoxLearningRateStepRatio.Size = new System.Drawing.Size(151, 25);
108 | this.textBoxLearningRateStepRatio.TabIndex = 16;
109 | this.textBoxLearningRateStepRatio.Text = "0.1";
110 | this.textBoxLearningRateStepRatio.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
111 | this.textBoxLearningRateStepRatio.TextChanged += new System.EventHandler(this.textBoxLearningRateStepRatio_TextChanged);
112 | //
113 | // textBoxInitialLearningRate
114 | //
115 | this.textBoxInitialLearningRate.Location = new System.Drawing.Point(278, 184);
116 | this.textBoxInitialLearningRate.Name = "textBoxInitialLearningRate";
117 | this.textBoxInitialLearningRate.Size = new System.Drawing.Size(151, 25);
118 | this.textBoxInitialLearningRate.TabIndex = 15;
119 | this.textBoxInitialLearningRate.Text = "0.001";
120 | this.textBoxInitialLearningRate.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
121 | this.textBoxInitialLearningRate.TextChanged += new System.EventHandler(this.textBoxInitialLearningRate_TextChanged);
122 | //
123 | // numericUpDownTrainingPercent
124 | //
125 | this.numericUpDownTrainingPercent.Location = new System.Drawing.Point(278, 221);
126 | this.numericUpDownTrainingPercent.Name = "numericUpDownTrainingPercent";
127 | this.numericUpDownTrainingPercent.Size = new System.Drawing.Size(154, 25);
128 | this.numericUpDownTrainingPercent.TabIndex = 14;
129 | this.numericUpDownTrainingPercent.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
130 | this.numericUpDownTrainingPercent.Value = new decimal(new int[] {
131 | 60,
132 | 0,
133 | 0,
134 | 0});
135 | this.numericUpDownTrainingPercent.ValueChanged += new System.EventHandler(this.numericUpDownTrainingPercent_ValueChanged);
136 | //
137 | // numericUpDownNumEpochs
138 | //
139 | this.numericUpDownNumEpochs.Location = new System.Drawing.Point(278, 73);
140 | this.numericUpDownNumEpochs.Name = "numericUpDownNumEpochs";
141 | this.numericUpDownNumEpochs.Size = new System.Drawing.Size(154, 25);
142 | this.numericUpDownNumEpochs.TabIndex = 12;
143 | this.numericUpDownNumEpochs.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
144 | this.numericUpDownNumEpochs.Value = new decimal(new int[] {
145 | 30,
146 | 0,
147 | 0,
148 | 0});
149 | this.numericUpDownNumEpochs.ValueChanged += new System.EventHandler(this.numericUpDownNumEpochs_ValueChanged);
150 | //
151 | // numericUpDownBatchSize
152 | //
153 | this.numericUpDownBatchSize.Location = new System.Drawing.Point(278, 36);
154 | this.numericUpDownBatchSize.Name = "numericUpDownBatchSize";
155 | this.numericUpDownBatchSize.Size = new System.Drawing.Size(154, 25);
156 | this.numericUpDownBatchSize.TabIndex = 11;
157 | this.numericUpDownBatchSize.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
158 | this.numericUpDownBatchSize.Value = new decimal(new int[] {
159 | 32,
160 | 0,
161 | 0,
162 | 0});
163 | this.numericUpDownBatchSize.ValueChanged += new System.EventHandler(this.numericUpDownBatchSize_ValueChanged);
164 | //
165 | // numericUpDownLearningRateSENE
166 | //
167 | this.numericUpDownLearningRateSENE.Location = new System.Drawing.Point(278, 110);
168 | this.numericUpDownLearningRateSENE.Name = "numericUpDownLearningRateSENE";
169 | this.numericUpDownLearningRateSENE.Size = new System.Drawing.Size(154, 25);
170 | this.numericUpDownLearningRateSENE.TabIndex = 10;
171 | this.numericUpDownLearningRateSENE.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
172 | this.numericUpDownLearningRateSENE.Value = new decimal(new int[] {
173 | 5,
174 | 0,
175 | 0,
176 | 0});
177 | this.numericUpDownLearningRateSENE.ValueChanged += new System.EventHandler(this.numericUpDownLearningRateSENE_ValueChanged);
178 | //
179 | // label7
180 | //
181 | this.label7.AutoSize = true;
182 | this.label7.Location = new System.Drawing.Point(127, 226);
183 | this.label7.Name = "label7";
184 | this.label7.Size = new System.Drawing.Size(135, 15);
185 | this.label7.TabIndex = 6;
186 | this.label7.Text = "TrainingPercent:";
187 | //
188 | // label5
189 | //
190 | this.label5.AutoSize = true;
191 | this.label5.Location = new System.Drawing.Point(95, 189);
192 | this.label5.Name = "label5";
193 | this.label5.Size = new System.Drawing.Size(167, 15);
194 | this.label5.TabIndex = 4;
195 | this.label5.Text = "InitialLearningRate:";
196 | //
197 | // label4
198 | //
199 | this.label4.AutoSize = true;
200 | this.label4.Location = new System.Drawing.Point(79, 152);
201 | this.label4.Name = "label4";
202 | this.label4.Size = new System.Drawing.Size(183, 15);
203 | this.label4.TabIndex = 3;
204 | this.label4.Text = "LearningRateStepRatio:";
205 | //
206 | // label3
207 | //
208 | this.label3.AutoSize = true;
209 | this.label3.Location = new System.Drawing.Point(15, 115);
210 | this.label3.Name = "label3";
211 | this.label3.Size = new System.Drawing.Size(247, 15);
212 | this.label3.TabIndex = 2;
213 | this.label3.Text = "LearningRateStepEveryNthEpoch:";
214 | //
215 | // label2
216 | //
217 | this.label2.AutoSize = true;
218 | this.label2.Location = new System.Drawing.Point(175, 78);
219 | this.label2.Name = "label2";
220 | this.label2.Size = new System.Drawing.Size(87, 15);
221 | this.label2.TabIndex = 1;
222 | this.label2.Text = "NumEpochs:";
223 | //
224 | // label1
225 | //
226 | this.label1.AutoSize = true;
227 | this.label1.Location = new System.Drawing.Point(175, 41);
228 | this.label1.Name = "label1";
229 | this.label1.Size = new System.Drawing.Size(87, 15);
230 | this.label1.TabIndex = 0;
231 | this.label1.Text = "BatchSize:";
232 | //
233 | // btnConfirm
234 | //
235 | this.btnConfirm.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
236 | this.btnConfirm.Location = new System.Drawing.Point(352, 319);
237 | this.btnConfirm.Name = "btnConfirm";
238 | this.btnConfirm.Size = new System.Drawing.Size(92, 40);
239 | this.btnConfirm.TabIndex = 1;
240 | this.btnConfirm.Text = "确定";
241 | this.btnConfirm.UseVisualStyleBackColor = true;
242 | this.btnConfirm.Click += new System.EventHandler(this.btnConfirm_Click);
243 | //
244 | // btnCancel
245 | //
246 | this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
247 | this.btnCancel.Location = new System.Drawing.Point(237, 319);
248 | this.btnCancel.Name = "btnCancel";
249 | this.btnCancel.Size = new System.Drawing.Size(92, 40);
250 | this.btnCancel.TabIndex = 2;
251 | this.btnCancel.Text = "取消";
252 | this.btnCancel.UseVisualStyleBackColor = true;
253 | this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
254 | //
255 | // ClassifierParamsSetForm
256 | //
257 | this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F);
258 | this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
259 | this.ClientSize = new System.Drawing.Size(473, 366);
260 | this.Controls.Add(this.btnCancel);
261 | this.Controls.Add(this.btnConfirm);
262 | this.Controls.Add(this.groupBox1);
263 | this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
264 | this.Name = "ClassifierParamsSetForm";
265 | this.Text = "参数设置";
266 | this.Load += new System.EventHandler(this.ClassifierParamsSetForm_Load);
267 | this.groupBox1.ResumeLayout(false);
268 | this.groupBox1.PerformLayout();
269 | ((System.ComponentModel.ISupportInitialize)(this.numericUpDownValidationPercent)).EndInit();
270 | ((System.ComponentModel.ISupportInitialize)(this.numericUpDownTrainingPercent)).EndInit();
271 | ((System.ComponentModel.ISupportInitialize)(this.numericUpDownNumEpochs)).EndInit();
272 | ((System.ComponentModel.ISupportInitialize)(this.numericUpDownBatchSize)).EndInit();
273 | ((System.ComponentModel.ISupportInitialize)(this.numericUpDownLearningRateSENE)).EndInit();
274 | this.ResumeLayout(false);
275 |
276 | }
277 |
278 | #endregion
279 |
280 | private System.Windows.Forms.GroupBox groupBox1;
281 | private System.Windows.Forms.Label label7;
282 | private System.Windows.Forms.Label label5;
283 | private System.Windows.Forms.Label label4;
284 | private System.Windows.Forms.Label label3;
285 | private System.Windows.Forms.Label label2;
286 | private System.Windows.Forms.Label label1;
287 | private System.Windows.Forms.NumericUpDown numericUpDownTrainingPercent;
288 | private System.Windows.Forms.NumericUpDown numericUpDownNumEpochs;
289 | private System.Windows.Forms.NumericUpDown numericUpDownBatchSize;
290 | private System.Windows.Forms.NumericUpDown numericUpDownLearningRateSENE;
291 | private System.Windows.Forms.TextBox textBoxInitialLearningRate;
292 | private System.Windows.Forms.TextBox textBoxLearningRateStepRatio;
293 | private System.Windows.Forms.Button btnConfirm;
294 | private System.Windows.Forms.Button btnCancel;
295 | private System.Windows.Forms.NumericUpDown numericUpDownValidationPercent;
296 | private System.Windows.Forms.Label label8;
297 | }
298 | }
--------------------------------------------------------------------------------
/DeepLearning_MNIST/ClassifierParamsSetForm.cs:
--------------------------------------------------------------------------------
1 | using HalconDotNet;
2 | using System;
3 | using System.Windows.Forms;
4 |
5 | namespace DeepLearning_MNIST
6 | {
7 | public partial class ClassifierParamsSetForm : Form
8 | {
9 | public ClassifierParamsSetForm()
10 | {
11 | InitializeComponent();
12 |
13 | }
14 |
15 |
16 | public HTuple _BatchSize = new HTuple();
17 | public HTuple _NumEpochs = new HTuple();
18 | public HTuple _InitialLearningRate = new HTuple();
19 | public HTuple _LearningRateStepEveryNthEpoch = new HTuple();
20 | public HTuple _LearningRateStepRatio = new HTuple();
21 | public HTuple _TrainingPercent = new HTuple();
22 | public HTuple _ValidationPercent = new HTuple();
23 |
24 |
25 | private void btnConfirm_Click(object sender, EventArgs e)
26 | {
27 | this.DialogResult = DialogResult.OK;
28 | this.Close();
29 |
30 | }
31 |
32 | private void btnCancel_Click(object sender, EventArgs e)
33 | {
34 | this.DialogResult = DialogResult.No;
35 | this.Close();
36 | }
37 |
38 | private void ClassifierParamsSetForm_Load(object sender, EventArgs e)
39 | {
40 | numericUpDownBatchSize.Value = _BatchSize;
41 | numericUpDownNumEpochs.Value = _NumEpochs;
42 | numericUpDownLearningRateSENE.Value = _LearningRateStepEveryNthEpoch;
43 | textBoxLearningRateStepRatio.Text = _LearningRateStepRatio.ToString();
44 | textBoxInitialLearningRate.Text = _InitialLearningRate.ToString();
45 | numericUpDownTrainingPercent.Value = _TrainingPercent;
46 | numericUpDownValidationPercent.Value = _ValidationPercent;
47 | }
48 |
49 | private void numericUpDownBatchSize_ValueChanged(object sender, EventArgs e)
50 | {
51 | if (Convert.ToInt32(numericUpDownBatchSize.Value) > 100 || Convert.ToInt32(numericUpDownBatchSize.Value) < 1)
52 | {
53 | return;
54 | }
55 | this._BatchSize = Convert.ToInt32(numericUpDownBatchSize.Value);
56 | btnConfirm.Focus();
57 | }
58 |
59 | private void numericUpDownNumEpochs_ValueChanged(object sender, EventArgs e)
60 | {
61 | if (Convert.ToInt32(numericUpDownNumEpochs.Value) > 100 || Convert.ToInt32(numericUpDownNumEpochs.Value) < 1)
62 | {
63 | return;
64 | }
65 | this._NumEpochs = Convert.ToInt32(numericUpDownNumEpochs.Value);
66 | btnConfirm.Focus();
67 | }
68 |
69 | private void numericUpDownLearningRateSENE_ValueChanged(object sender, EventArgs e)
70 | {
71 | if (Convert.ToInt32(numericUpDownLearningRateSENE.Value) > 100 || Convert.ToInt32(numericUpDownLearningRateSENE.Value) < 1)
72 | {
73 | return;
74 | }
75 | this._LearningRateStepEveryNthEpoch = Convert.ToInt32(numericUpDownLearningRateSENE.Value);
76 | btnConfirm.Focus();
77 | }
78 |
79 | private void textBoxLearningRateStepRatio_TextChanged(object sender, EventArgs e)
80 | {
81 | this._LearningRateStepRatio = Convert.ToDouble(textBoxLearningRateStepRatio.Text);
82 | btnConfirm.Focus();
83 | }
84 |
85 | private void textBoxInitialLearningRate_TextChanged(object sender, EventArgs e)
86 | {
87 | this._InitialLearningRate = Convert.ToDouble(textBoxInitialLearningRate.Text);
88 | btnConfirm.Focus();
89 | }
90 |
91 |
92 | private void numericUpDownTrainingPercent_ValueChanged(object sender, EventArgs e)
93 | {
94 | if (Convert.ToInt32(numericUpDownTrainingPercent.Value) > 100 || Convert.ToInt32(numericUpDownTrainingPercent.Value) < 1)
95 | {
96 | return;
97 | }
98 | this._TrainingPercent = Convert.ToInt32(numericUpDownTrainingPercent.Value);
99 | btnConfirm.Focus();
100 | }
101 |
102 | private void numericUpDownValidationPercent_ValueChanged(object sender, EventArgs e)
103 | {
104 | if (Convert.ToInt32(numericUpDownValidationPercent.Value) > 100 || Convert.ToInt32(numericUpDownValidationPercent.Value) < 1)
105 | {
106 | return;
107 | }
108 | this._ValidationPercent = Convert.ToInt32(numericUpDownValidationPercent.Value);
109 | btnConfirm.Focus();
110 | }
111 |
112 | }
113 | }
114 |
--------------------------------------------------------------------------------
/DeepLearning_MNIST/DeepLearning_MNIST.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {86425A08-EFBA-44AF-AA45-C5F71AFFB21B}
8 | WinExe
9 | Properties
10 | DeepLearning_MNIST
11 | DeepLearning_MNIST
12 | v4.5.2
13 | 512
14 | true
15 |
16 |
17 | AnyCPU
18 | true
19 | full
20 | false
21 | bin\Debug\
22 | DEBUG;TRACE
23 | prompt
24 | 4
25 | false
26 |
27 |
28 | AnyCPU
29 | pdbonly
30 | true
31 | bin\Release\
32 | TRACE
33 | prompt
34 | 4
35 |
36 |
37 |
38 | C:\Program Files\MVTec\HALCON-19.05-Progress\bin\dotnet35\halcondotnet.dll
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 | Form
59 |
60 |
61 | ClassifierParamsSetForm.cs
62 |
63 |
64 | Form
65 |
66 |
67 | Form1.cs
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 | ClassifierParamsSetForm.cs
78 |
79 |
80 | Form1.cs
81 |
82 |
83 | ResXFileCodeGenerator
84 | Resources.Designer.cs
85 | Designer
86 |
87 |
88 | True
89 | Resources.resx
90 |
91 |
92 | SettingsSingleFileGenerator
93 | Settings.Designer.cs
94 |
95 |
96 | True
97 | Settings.settings
98 | True
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 | Always
107 |
108 |
109 |
110 |
117 |
--------------------------------------------------------------------------------
/DeepLearning_MNIST/Form1.Designer.cs:
--------------------------------------------------------------------------------
1 | namespace DeepLearning_MNIST
2 | {
3 | partial class Form1
4 | {
5 | ///
6 | /// 必需的设计器变量。
7 | ///
8 | private System.ComponentModel.IContainer components = null;
9 |
10 | ///
11 | /// 清理所有正在使用的资源。
12 | ///
13 | /// 如果应释放托管资源,为 true;否则为 false。
14 | protected override void Dispose(bool disposing)
15 | {
16 | if (disposing && (components != null))
17 | {
18 | components.Dispose();
19 | }
20 | base.Dispose(disposing);
21 | }
22 |
23 | #region Windows 窗体设计器生成的代码
24 |
25 | ///
26 | /// 设计器支持所需的方法 - 不要修改
27 | /// 使用代码编辑器修改此方法的内容。
28 | ///
29 | private void InitializeComponent()
30 | {
31 | System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
32 | this.hWindowControl1 = new HalconDotNet.HWindowControl();
33 | this.btnPreprocessImages = new System.Windows.Forms.Button();
34 | this.btnTrainClassifier = new System.Windows.Forms.Button();
35 | this.btnTest = new System.Windows.Forms.Button();
36 | this.textBoxInformation = new System.Windows.Forms.TextBox();
37 | this.groupBox1 = new System.Windows.Forms.GroupBox();
38 | this.btnRandomTest = new System.Windows.Forms.Button();
39 | this.btnChooseTestImage = new System.Windows.Forms.Button();
40 | this.btnReadClassifier = new System.Windows.Forms.Button();
41 | this.groupBox2 = new System.Windows.Forms.GroupBox();
42 | this.btnComputeConfusionMatrix = new System.Windows.Forms.Button();
43 | this.btnSaveClassifier = new System.Windows.Forms.Button();
44 | this.btnClassifierParamsSet = new System.Windows.Forms.Button();
45 | this.groupBox3 = new System.Windows.Forms.GroupBox();
46 | this.btnChooseFolder = new System.Windows.Forms.Button();
47 | this.label1 = new System.Windows.Forms.Label();
48 | this.btnReadInformation = new System.Windows.Forms.Button();
49 | this.btnClearText = new System.Windows.Forms.Button();
50 | this.btnShowParams = new System.Windows.Forms.Button();
51 | this.groupBox1.SuspendLayout();
52 | this.groupBox2.SuspendLayout();
53 | this.groupBox3.SuspendLayout();
54 | this.SuspendLayout();
55 | //
56 | // hWindowControl1
57 | //
58 | this.hWindowControl1.BackColor = System.Drawing.Color.Black;
59 | this.hWindowControl1.BorderColor = System.Drawing.Color.Black;
60 | this.hWindowControl1.ImagePart = new System.Drawing.Rectangle(0, 0, 640, 480);
61 | this.hWindowControl1.Location = new System.Drawing.Point(2, 3);
62 | this.hWindowControl1.Name = "hWindowControl1";
63 | this.hWindowControl1.Size = new System.Drawing.Size(640, 480);
64 | this.hWindowControl1.TabIndex = 0;
65 | this.hWindowControl1.WindowSize = new System.Drawing.Size(640, 480);
66 | //
67 | // btnPreprocessImages
68 | //
69 | this.btnPreprocessImages.Location = new System.Drawing.Point(135, 39);
70 | this.btnPreprocessImages.Name = "btnPreprocessImages";
71 | this.btnPreprocessImages.Size = new System.Drawing.Size(100, 40);
72 | this.btnPreprocessImages.TabIndex = 1;
73 | this.btnPreprocessImages.Text = "预处理图像";
74 | this.btnPreprocessImages.UseVisualStyleBackColor = true;
75 | this.btnPreprocessImages.Click += new System.EventHandler(this.btnPreprocessImages_Click);
76 | //
77 | // btnTrainClassifier
78 | //
79 | this.btnTrainClassifier.Location = new System.Drawing.Point(90, 39);
80 | this.btnTrainClassifier.Name = "btnTrainClassifier";
81 | this.btnTrainClassifier.Size = new System.Drawing.Size(100, 40);
82 | this.btnTrainClassifier.TabIndex = 2;
83 | this.btnTrainClassifier.Text = "训练分类器";
84 | this.btnTrainClassifier.UseVisualStyleBackColor = true;
85 | this.btnTrainClassifier.Click += new System.EventHandler(this.btnTrainClassifier_Click);
86 | //
87 | // btnTest
88 | //
89 | this.btnTest.Location = new System.Drawing.Point(199, 21);
90 | this.btnTest.Name = "btnTest";
91 | this.btnTest.Size = new System.Drawing.Size(88, 35);
92 | this.btnTest.TabIndex = 3;
93 | this.btnTest.Text = "测试";
94 | this.btnTest.UseVisualStyleBackColor = true;
95 | this.btnTest.Click += new System.EventHandler(this.btnTest_Click);
96 | //
97 | // textBoxInformation
98 | //
99 | this.textBoxInformation.Location = new System.Drawing.Point(651, 27);
100 | this.textBoxInformation.Multiline = true;
101 | this.textBoxInformation.Name = "textBoxInformation";
102 | this.textBoxInformation.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
103 | this.textBoxInformation.Size = new System.Drawing.Size(285, 410);
104 | this.textBoxInformation.TabIndex = 4;
105 | //
106 | // groupBox1
107 | //
108 | this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
109 | this.groupBox1.Controls.Add(this.btnRandomTest);
110 | this.groupBox1.Controls.Add(this.btnChooseTestImage);
111 | this.groupBox1.Controls.Add(this.btnReadClassifier);
112 | this.groupBox1.Controls.Add(this.btnTest);
113 | this.groupBox1.Location = new System.Drawing.Point(643, 492);
114 | this.groupBox1.Name = "groupBox1";
115 | this.groupBox1.Size = new System.Drawing.Size(295, 100);
116 | this.groupBox1.TabIndex = 6;
117 | this.groupBox1.TabStop = false;
118 | this.groupBox1.Text = "3、图像识别测试";
119 | //
120 | // btnRandomTest
121 | //
122 | this.btnRandomTest.Location = new System.Drawing.Point(107, 60);
123 | this.btnRandomTest.Name = "btnRandomTest";
124 | this.btnRandomTest.Size = new System.Drawing.Size(180, 35);
125 | this.btnRandomTest.TabIndex = 6;
126 | this.btnRandomTest.Text = "随机选择图片测试";
127 | this.btnRandomTest.UseVisualStyleBackColor = true;
128 | this.btnRandomTest.Click += new System.EventHandler(this.btnRandomTest_Click);
129 | //
130 | // btnChooseTestImage
131 | //
132 | this.btnChooseTestImage.Location = new System.Drawing.Point(107, 21);
133 | this.btnChooseTestImage.Name = "btnChooseTestImage";
134 | this.btnChooseTestImage.Size = new System.Drawing.Size(88, 35);
135 | this.btnChooseTestImage.TabIndex = 5;
136 | this.btnChooseTestImage.Text = "选择图片";
137 | this.btnChooseTestImage.UseVisualStyleBackColor = true;
138 | this.btnChooseTestImage.Click += new System.EventHandler(this.btnChooseTestImage_Click);
139 | //
140 | // btnReadClassifier
141 | //
142 | this.btnReadClassifier.Location = new System.Drawing.Point(3, 39);
143 | this.btnReadClassifier.Name = "btnReadClassifier";
144 | this.btnReadClassifier.Size = new System.Drawing.Size(101, 40);
145 | this.btnReadClassifier.TabIndex = 4;
146 | this.btnReadClassifier.Text = "读取分类器";
147 | this.btnReadClassifier.UseVisualStyleBackColor = true;
148 | this.btnReadClassifier.Click += new System.EventHandler(this.btnReadClassifier_Click);
149 | //
150 | // groupBox2
151 | //
152 | this.groupBox2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
153 | this.groupBox2.Controls.Add(this.btnComputeConfusionMatrix);
154 | this.groupBox2.Controls.Add(this.btnSaveClassifier);
155 | this.groupBox2.Controls.Add(this.btnClassifierParamsSet);
156 | this.groupBox2.Controls.Add(this.btnTrainClassifier);
157 | this.groupBox2.Location = new System.Drawing.Point(252, 492);
158 | this.groupBox2.Name = "groupBox2";
159 | this.groupBox2.Size = new System.Drawing.Size(385, 100);
160 | this.groupBox2.TabIndex = 7;
161 | this.groupBox2.TabStop = false;
162 | this.groupBox2.Text = "2、训练分类器";
163 | //
164 | // btnComputeConfusionMatrix
165 | //
166 | this.btnComputeConfusionMatrix.Location = new System.Drawing.Point(298, 39);
167 | this.btnComputeConfusionMatrix.Name = "btnComputeConfusionMatrix";
168 | this.btnComputeConfusionMatrix.Size = new System.Drawing.Size(80, 40);
169 | this.btnComputeConfusionMatrix.TabIndex = 5;
170 | this.btnComputeConfusionMatrix.Text = "误差分析";
171 | this.btnComputeConfusionMatrix.UseVisualStyleBackColor = true;
172 | this.btnComputeConfusionMatrix.Click += new System.EventHandler(this.btnComputeConfusionMatrix_Click);
173 | //
174 | // btnSaveClassifier
175 | //
176 | this.btnSaveClassifier.Location = new System.Drawing.Point(194, 39);
177 | this.btnSaveClassifier.Name = "btnSaveClassifier";
178 | this.btnSaveClassifier.Size = new System.Drawing.Size(100, 40);
179 | this.btnSaveClassifier.TabIndex = 4;
180 | this.btnSaveClassifier.Text = "保存分类器";
181 | this.btnSaveClassifier.UseVisualStyleBackColor = true;
182 | this.btnSaveClassifier.Click += new System.EventHandler(this.btnSaveClassifier_Click);
183 | //
184 | // btnClassifierParamsSet
185 | //
186 | this.btnClassifierParamsSet.Location = new System.Drawing.Point(6, 39);
187 | this.btnClassifierParamsSet.Name = "btnClassifierParamsSet";
188 | this.btnClassifierParamsSet.Size = new System.Drawing.Size(80, 40);
189 | this.btnClassifierParamsSet.TabIndex = 3;
190 | this.btnClassifierParamsSet.Text = "参数设置";
191 | this.btnClassifierParamsSet.UseVisualStyleBackColor = true;
192 | this.btnClassifierParamsSet.Click += new System.EventHandler(this.btnClassifierParamsSet_Click);
193 | //
194 | // groupBox3
195 | //
196 | this.groupBox3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
197 | this.groupBox3.Controls.Add(this.btnChooseFolder);
198 | this.groupBox3.Controls.Add(this.btnPreprocessImages);
199 | this.groupBox3.Location = new System.Drawing.Point(5, 492);
200 | this.groupBox3.Name = "groupBox3";
201 | this.groupBox3.Size = new System.Drawing.Size(241, 100);
202 | this.groupBox3.TabIndex = 8;
203 | this.groupBox3.TabStop = false;
204 | this.groupBox3.Text = "1、预处理图像";
205 | //
206 | // btnChooseFolder
207 | //
208 | this.btnChooseFolder.Location = new System.Drawing.Point(7, 39);
209 | this.btnChooseFolder.Name = "btnChooseFolder";
210 | this.btnChooseFolder.Size = new System.Drawing.Size(122, 40);
211 | this.btnChooseFolder.TabIndex = 2;
212 | this.btnChooseFolder.Text = "选择图像文件夹";
213 | this.btnChooseFolder.UseVisualStyleBackColor = true;
214 | this.btnChooseFolder.Click += new System.EventHandler(this.btnChooseFolder_Click);
215 | //
216 | // label1
217 | //
218 | this.label1.AutoSize = true;
219 | this.label1.Location = new System.Drawing.Point(648, 9);
220 | this.label1.Name = "label1";
221 | this.label1.Size = new System.Drawing.Size(82, 15);
222 | this.label1.TabIndex = 5;
223 | this.label1.Text = "提示信息:";
224 | //
225 | // btnReadInformation
226 | //
227 | this.btnReadInformation.Location = new System.Drawing.Point(651, 443);
228 | this.btnReadInformation.Name = "btnReadInformation";
229 | this.btnReadInformation.Size = new System.Drawing.Size(90, 35);
230 | this.btnReadInformation.TabIndex = 9;
231 | this.btnReadInformation.Text = "查看说明";
232 | this.btnReadInformation.UseVisualStyleBackColor = true;
233 | this.btnReadInformation.Click += new System.EventHandler(this.btnReadInformation_Click);
234 | //
235 | // btnClearText
236 | //
237 | this.btnClearText.Location = new System.Drawing.Point(846, 442);
238 | this.btnClearText.Name = "btnClearText";
239 | this.btnClearText.Size = new System.Drawing.Size(90, 35);
240 | this.btnClearText.TabIndex = 10;
241 | this.btnClearText.Text = "清空信息";
242 | this.btnClearText.UseVisualStyleBackColor = true;
243 | this.btnClearText.Click += new System.EventHandler(this.btnClearText_Click);
244 | //
245 | // btnShowParams
246 | //
247 | this.btnShowParams.Location = new System.Drawing.Point(750, 442);
248 | this.btnShowParams.Name = "btnShowParams";
249 | this.btnShowParams.Size = new System.Drawing.Size(90, 35);
250 | this.btnShowParams.TabIndex = 11;
251 | this.btnShowParams.Text = "查看参数";
252 | this.btnShowParams.UseVisualStyleBackColor = true;
253 | this.btnShowParams.Click += new System.EventHandler(this.btnShowParams_Click);
254 | //
255 | // Form1
256 | //
257 | this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
258 | this.BackColor = System.Drawing.SystemColors.Control;
259 | this.ClientSize = new System.Drawing.Size(942, 598);
260 | this.Controls.Add(this.btnShowParams);
261 | this.Controls.Add(this.btnClearText);
262 | this.Controls.Add(this.btnReadInformation);
263 | this.Controls.Add(this.label1);
264 | this.Controls.Add(this.textBoxInformation);
265 | this.Controls.Add(this.groupBox3);
266 | this.Controls.Add(this.groupBox2);
267 | this.Controls.Add(this.groupBox1);
268 | this.Controls.Add(this.hWindowControl1);
269 | this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
270 | this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
271 | this.MaximizeBox = false;
272 | this.Name = "Form1";
273 | this.Text = "DeepLearningDemo之MNIST数据集";
274 | this.Load += new System.EventHandler(this.Form1_Load);
275 | this.groupBox1.ResumeLayout(false);
276 | this.groupBox2.ResumeLayout(false);
277 | this.groupBox3.ResumeLayout(false);
278 | this.ResumeLayout(false);
279 | this.PerformLayout();
280 |
281 | }
282 |
283 | #endregion
284 |
285 | private HalconDotNet.HWindowControl hWindowControl1;
286 | private System.Windows.Forms.Button btnPreprocessImages;
287 | private System.Windows.Forms.Button btnTrainClassifier;
288 | private System.Windows.Forms.Button btnTest;
289 | private System.Windows.Forms.TextBox textBoxInformation;
290 | private System.Windows.Forms.GroupBox groupBox1;
291 | private System.Windows.Forms.Button btnChooseTestImage;
292 | private System.Windows.Forms.Button btnReadClassifier;
293 | private System.Windows.Forms.GroupBox groupBox2;
294 | private System.Windows.Forms.Button btnSaveClassifier;
295 | private System.Windows.Forms.Button btnClassifierParamsSet;
296 | private System.Windows.Forms.GroupBox groupBox3;
297 | private System.Windows.Forms.Button btnChooseFolder;
298 | private System.Windows.Forms.Button btnRandomTest;
299 | private System.Windows.Forms.Button btnComputeConfusionMatrix;
300 | private System.Windows.Forms.Label label1;
301 | private System.Windows.Forms.Button btnReadInformation;
302 | private System.Windows.Forms.Button btnClearText;
303 | private System.Windows.Forms.Button btnShowParams;
304 | }
305 | }
306 |
307 |
--------------------------------------------------------------------------------
/DeepLearning_MNIST/Form1.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.ComponentModel;
4 | using System.Data;
5 | using System.Drawing;
6 | using System.Linq;
7 | using System.Text;
8 | using System.Threading.Tasks;
9 | using System.Windows.Forms;
10 | using HalconDotNet;
11 | using System.IO;
12 |
13 | namespace DeepLearning_MNIST
14 | {
15 | public partial class Form1 : Form
16 | {
17 | public Form1()
18 | {
19 | InitializeComponent();
20 | }
21 |
22 | #region 变量声明
23 | //创建对象
24 | MNIST mnist = new MNIST();
25 |
26 | #endregion
27 |
28 | private void Form1_Load(object sender, EventArgs e)
29 | {
30 | this.mnist.hv_HWindowControl = this.hWindowControl1;
31 | groupBox2.Enabled = false;
32 | groupBox1.Enabled = false;
33 | HOperatorSet.DispText(this.hWindowControl1.HalconWindow, "请先选择图像目录", "window", "center", "center", "white", "box", "false");
34 | textBoxInformation.Text = "请先选择图像目录";
35 | btnChooseFolder.Focus();
36 | }
37 |
38 | private void btnPreprocessImages_Click(object sender, EventArgs e)
39 | {
40 | if (this.mnist.mnist_Preprocess.path_Images == null)
41 | {
42 | MessageBox.Show("请先选择图像目录");
43 | return;
44 | }
45 |
46 | this.mnist.mnist_Preprocess.path_Train_Images = this.mnist.mnist_Preprocess.path_Images + @"\Train_images";
47 | if (!IsPathAvailable(this.mnist.mnist_Preprocess.path_Train_Images))
48 | {
49 | return;
50 | }
51 |
52 | this.mnist.mnist_Preprocess.path_Preprocessed_Images = mnist.mnist_Preprocess.path_Images + @"\Preprocessed_images";
53 | if (Directory.Exists(this.mnist.mnist_Preprocess.path_Preprocessed_Images))
54 | {
55 | if (MessageBox.Show("正在新建预处理图像保存目录,但该目录已存在,是否删除并继续?", "消息确认", MessageBoxButtons.OKCancel) == DialogResult.OK)
56 | {
57 | //删除已有文件夹及其子文件夹和文件
58 | HalconTools.remove_dir_recursively(this.mnist.mnist_Preprocess.path_Preprocessed_Images);
59 | }
60 | else { return; }
61 | }
62 |
63 | mnist.PreprocessImages();
64 | }
65 |
66 | private void btnChooseFolder_Click(object sender, EventArgs e)
67 | {
68 |
69 | FolderBrowserDialog fbd = new FolderBrowserDialog();
70 | fbd.Description = "请选择文件路径";
71 | fbd.SelectedPath = Application.StartupPath;
72 |
73 | if (fbd.ShowDialog() == DialogResult.OK)
74 | {
75 | this.mnist.mnist_Preprocess.path_Images = fbd.SelectedPath;
76 | if (fbd.SelectedPath.Contains("Train") || fbd.SelectedPath.Contains("Test") || fbd.SelectedPath.Contains("Preprocessed"))
77 | {
78 | this.mnist.mnist_Preprocess.path_Images = Path.GetDirectoryName(fbd.SelectedPath);
79 | }
80 |
81 | StringBuilder sb = new StringBuilder();
82 | sb.Append("已选择目录:\r\n");
83 | sb.Append(mnist.mnist_Preprocess.GetImagesPaths());
84 | this.textBoxInformation.Text = sb.ToString();
85 | HOperatorSet.ClearWindow(this.hWindowControl1.HalconWindow);
86 | groupBox2.Enabled = true;
87 | groupBox1.Enabled = true;
88 | }
89 | }
90 |
91 | private void btnClassifierParamsSet_Click(object sender, EventArgs e)
92 | {
93 | ClassifierParamsSetForm cpsf = new ClassifierParamsSetForm();
94 |
95 | cpsf._BatchSize = this.mnist.mnist_Train.hv_BatchSize;
96 | cpsf._NumEpochs = this.mnist.mnist_Train.hv_NumEpochs;
97 | cpsf._LearningRateStepEveryNthEpoch = this.mnist.mnist_Train.hv_LearningRateStepEveryNthEpoch;
98 | cpsf._LearningRateStepRatio = this.mnist.mnist_Train.hv_LearningRateStepRatio;
99 | cpsf._InitialLearningRate = this.mnist.mnist_Train.hv_InitialLearningRate;
100 | cpsf._TrainingPercent = this.mnist.mnist_Train.hv_TrainingPercent;
101 | cpsf._ValidationPercent = this.mnist.mnist_Train.hv_ValidationPercent;
102 |
103 | if (cpsf.ShowDialog() == DialogResult.OK)
104 | {
105 | this.mnist.mnist_Train.hv_BatchSize = cpsf._BatchSize;
106 | this.mnist.mnist_Train.hv_NumEpochs = cpsf._NumEpochs;
107 | this.mnist.mnist_Train.hv_LearningRateStepEveryNthEpoch = cpsf._LearningRateStepEveryNthEpoch;
108 | this.mnist.mnist_Train.hv_LearningRateStepRatio = cpsf._LearningRateStepRatio;
109 | this.mnist.mnist_Train.hv_InitialLearningRate = cpsf._InitialLearningRate;
110 | this.mnist.mnist_Train.hv_TrainingPercent = cpsf._TrainingPercent;
111 | this.mnist.mnist_Train.hv_ValidationPercent = cpsf._ValidationPercent;
112 | }
113 | StringBuilder sb = new StringBuilder();
114 |
115 | sb.Append("当前训练参数设置:\r\n");
116 | sb.Append(mnist.mnist_Train.TrainClassifierParams());
117 | this.textBoxInformation.Text = sb.ToString();
118 | }
119 |
120 | private void btnTrainClassifier_Click(object sender, EventArgs e)
121 | {
122 | //获取预处理后图像的文件夹名称
123 | mnist.mnist_Train.hv_PreprocessedFolder = mnist.mnist_Preprocess.path_Images + @"\Preprocessed_images";
124 | if (!IsPathAvailable(mnist.mnist_Train.hv_PreprocessedFolder))
125 | {
126 | return;
127 | }
128 |
129 |
130 | StringBuilder sb = new StringBuilder();
131 |
132 | sb.Append("训练进行中...\r\n\r\n").Append("当前训练参数设置:\r\n");
133 | sb.Append(mnist.mnist_Train.TrainClassifierParams());
134 | this.textBoxInformation.Text = sb.ToString();
135 |
136 | mnist.Trainclassifier();
137 | }
138 |
139 | private void btnSaveClassifier_Click(object sender, EventArgs e)
140 | {
141 | if (this.mnist.mnist_Train.hv_Train_DLClassifierHandle == null)
142 | {
143 | MessageBox.Show("无可保存的分类器", "错误信息");
144 | return;
145 | }
146 | SaveFileDialog sfd = new SaveFileDialog();
147 | sfd.InitialDirectory = Application.StartupPath;
148 | sfd.FileName = Path.GetFileName(mnist.mnist_Train.hv_Trained_DlClassifierName);
149 | sfd.Filter = "(分类器文件*.hdl)|*.hdl";
150 | if (sfd.ShowDialog() == DialogResult.OK)
151 | {
152 | if (!sfd.FileName.Contains(".hdl"))
153 | {
154 | sfd.FileName = sfd.FileName + ".hdl";
155 | }
156 | HOperatorSet.WriteDlClassifier(this.mnist.mnist_Train.hv_Train_DLClassifierHandle, sfd.FileName);
157 | this.textBoxInformation.Text = "分类器已保存:\r\n" + sfd.FileName;
158 |
159 | }
160 | }
161 |
162 | private void btnReadClassifier_Click(object sender, EventArgs e)
163 | {
164 | OpenFileDialog ofd = new OpenFileDialog();
165 | ofd.InitialDirectory = Application.StartupPath;
166 | ofd.Multiselect = false;
167 | ofd.Filter = "classifier文件(*.hdl)|*.hdl";
168 | ofd.Title = "选择测试分类器";
169 |
170 | if (ofd.ShowDialog() == DialogResult.OK)
171 | {
172 | mnist.mnist_Test.hv_Test_DlClassifierName = ofd.FileName;
173 | this.textBoxInformation.Text = "已选择分类器:\r\n" + mnist.mnist_Test.hv_Test_DlClassifierName.ToString();
174 | }
175 | }
176 |
177 | private void btnRandomTest_Click(object sender, EventArgs e)
178 | {
179 | mnist.mnist_Test.path_Test_Images = mnist.mnist_Preprocess.path_Images + @"\Test_images";
180 | if (mnist.mnist_Preprocess.path_Images.Contains("Test"))
181 | {
182 | mnist.mnist_Test.path_Test_Images = mnist.mnist_Preprocess.path_Images;
183 | }
184 | //判断图像文件夹是否存在或内容是否为空
185 | if (!IsPathAvailable(mnist.mnist_Test.path_Test_Images))
186 | {
187 | return;
188 | }
189 |
190 | mnist.mnist_Test.RandomGetImage();
191 | textBoxInformation.Text = "已选择测试图像:\r\n" + mnist.mnist_Test.ho_TestImageName;
192 |
193 | mnist.Testclassifier();
194 | }
195 |
196 | private void btnChooseTestImage_Click(object sender, EventArgs e)
197 | {
198 | OpenFileDialog ofd = new OpenFileDialog();
199 | ofd.InitialDirectory = this.mnist.mnist_Preprocess.path_Images;
200 | ofd.Multiselect = false;
201 | ofd.Filter = "图像文件(*.bmp;*.png;*.jpg;*.jpeg;*.tif)|*.bmp;*.png;*.jpg;*.jpeg;*.tif";
202 |
203 | if (ofd.ShowDialog() == DialogResult.OK)
204 | {
205 | HOperatorSet.ReadImage(out this.mnist.mnist_Test.ho_TestImage, ofd.FileName);
206 | mnist.DispImageAdaptively(ref this.hWindowControl1, this.mnist.mnist_Test.ho_TestImage);
207 | textBoxInformation.Text = "已选择测试图像:\r\n" + ofd.FileName;
208 | }
209 | }
210 |
211 | private void btnTest_Click(object sender, EventArgs e)
212 | {
213 | if (mnist.mnist_Test.ho_TestImage == null)
214 | {
215 | MessageBox.Show("请选择新图像", "错误提示");
216 | return;
217 | }
218 |
219 | mnist.Testclassifier();
220 | }
221 |
222 | private void btnReadInformation_Click(object sender, EventArgs e)
223 | {
224 | this.textBoxInformation.Text = mnist.InformationText();
225 | }
226 |
227 | private void btnClearText_Click(object sender, EventArgs e)
228 | {
229 | this.textBoxInformation.Text = "";
230 | }
231 |
232 | private void btnComputeConfusionMatrix_Click(object sender, EventArgs e)
233 | {
234 | if (this.mnist.mnist_Train.hv_Train_DLClassifierHandle == null)
235 | {
236 | MessageBox.Show("请先训练分类器");
237 | return;
238 | }
239 | mnist.mnist_Train.ComputeConfusionMatrix(this.hWindowControl1.HalconWindow);
240 |
241 | StringBuilder sb = new StringBuilder();
242 | sb.Append("当前训练参数设置:\r\n");
243 | sb.Append(mnist.mnist_Train.TrainClassifierParams());
244 | this.textBoxInformation.Text = sb.ToString();
245 | }
246 |
247 | private void btnShowParams_Click(object sender, EventArgs e)
248 | {
249 | StringBuilder sb = new StringBuilder();
250 |
251 | sb.Append("当前训练参数设置:\r\n");
252 | sb.Append(mnist.mnist_Train.TrainClassifierParams());
253 |
254 | sb.Append("\r\n当前分类器:\r\n");
255 | if (mnist.mnist_Train.hv_Trained_DlClassifierName != null)
256 | {
257 | sb.Append(mnist.mnist_Train.hv_Trained_DlClassifierName.ToString() + "\r\n");
258 | }
259 | else if (mnist.mnist_Test.hv_Test_DlClassifierName != null)
260 | {
261 | sb.Append(mnist.mnist_Test.hv_Test_DlClassifierName.ToString() + "\r\n");
262 | }
263 | else
264 | {
265 | sb.Append("暂无可用分类器,需要训练或读取\r\n");
266 | }
267 |
268 |
269 | sb.Append("\r\n当前图像文件目录:\r\n");
270 | sb.Append(mnist.mnist_Preprocess.GetImagesPaths());
271 |
272 | this.textBoxInformation.Text = sb.ToString();
273 | }
274 |
275 | ///
276 | /// 判断路径是否存在或内容是否为空
277 | ///
278 | public bool IsPathAvailable(string Path)
279 | {
280 | if (!Directory.Exists(Path))
281 | {
282 | MessageBox.Show(Path+"路径不存在", "错误提示");
283 | return false;
284 | }
285 | if (Directory.GetDirectories(Path).Length < 1 && Directory.GetFiles(Path).Length < 1)
286 | {
287 | MessageBox.Show(Path+"路径内容为空", "错误提示");
288 | return false;
289 | }
290 | return true;
291 | }
292 |
293 | }
294 | }
295 |
--------------------------------------------------------------------------------
/DeepLearning_MNIST/MNIST.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 | using HalconDotNet;
7 | using System.Windows.Forms;
8 | using System.IO;
9 |
10 | namespace DeepLearning_MNIST
11 | {
12 | class MNIST : HalconTools
13 | {
14 |
15 | #region
16 |
17 | public Preprocess mnist_Preprocess = new Preprocess();
18 | public Train mnist_Train = new Train();
19 | public Test mnist_Test = new Test();
20 |
21 | //窗口句柄
22 | public HWindowControl hv_HWindowControl = new HWindowControl();
23 |
24 | //分类模型
25 | // HALCON provides pretrained neural networks. These neural networks are good starting points to train a custom classifier for image classification. They have been pretrained on a large image dataset. The provided pretrained neural networks are:
26 | // "pretrained_dl_classifier_compact.hdl"
27 | // This neural network is designed to be memory and runtime efficient.This network does not contain any fully connected layer. The network architecture allows changes concerning the image dimensions, but requires a minimum 'image_width' and 'image_height' of 15 pixels.
28 | // "pretrained_dl_classifier_enhanced.hdl"
29 | // This neural network has more hidden layers than 'pretrained_dl_classifier_compact.hdl' and is therefore assumed to be better suited for more complex classification tasks. But this comes at the cost of being more time and memory demanding.
30 | // "pretrained_dl_classifier_resnet50.hdl"
31 | // As the neural network 'pretrained_dl_classifier_enhanced.hdl', this classifier is suited for more complex tasks. But its structure differs, bringing the advantage of making the training more stable and being internally more robust.
32 | public string hv_Pretrained_DlClassifierName = "pretrained_dl_classifier_compact.hdl";
33 | #endregion
34 |
35 | public MNIST()
36 | { }
37 |
38 | public void PreprocessImages()
39 | {
40 | mnist_Preprocess.PreprocessDlClassifierImagesForTrain(this.hv_HWindowControl, hv_Pretrained_DlClassifierName);
41 |
42 | }
43 |
44 | public void Trainclassifier()
45 | {
46 | //分类器默认保存名称为"classifier+图像主文件夹名称.hdl"
47 | mnist_Train.hv_Trained_DlClassifierName = "classifier_" + Path.GetFileNameWithoutExtension(mnist_Preprocess.path_Images) + ".hdl";
48 |
49 | //训练分类器
50 | mnist_Train.TrainProcess(this.hv_HWindowControl.HalconWindow, hv_Pretrained_DlClassifierName);
51 |
52 | }
53 |
54 | public void Testclassifier()
55 | {
56 | GetDlClassifierName();
57 |
58 | mnist_Preprocess.PreprocessImage(this.hv_Pretrained_DlClassifierName,mnist_Test.ho_TestImage,out mnist_Test.ho_Preprocessed_TestImage);
59 | mnist_Test.TestImage(ref hv_HWindowControl);
60 | }
61 |
62 | public string InformationText()
63 | {
64 | string strReadFilePath = "Readme.txt";
65 | StreamReader srReadFile = new StreamReader(strReadFilePath, Encoding.Default);
66 | StringBuilder Introduction = new StringBuilder();
67 | // 读取流直至文件末尾结束
68 | while (!srReadFile.EndOfStream)
69 | {
70 | Introduction.Append(srReadFile.ReadLine() + "\r\n");
71 | }
72 | // 关闭读取流文件
73 | srReadFile.Close();
74 |
75 | return Introduction.ToString();
76 | }
77 |
78 | public void GetDlClassifierName()
79 | {
80 | if (mnist_Test.hv_Test_DlClassifierName == null)
81 | {
82 | if (mnist_Train.hv_Trained_DlClassifierName == null)
83 | {
84 | MessageBox.Show("无可用分类器,请先训练或读取", "错误提示");
85 | return;
86 | }
87 | mnist_Test.hv_Test_DlClassifierName = mnist_Train.hv_Trained_DlClassifierName;
88 | }
89 | }
90 |
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/DeepLearning_MNIST/Preprocess.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 | using HalconDotNet;
7 | using System.IO;
8 | using System.Windows.Forms;
9 |
10 | namespace DeepLearning_MNIST
11 | {
12 | public class Preprocess : HalconTools
13 | {
14 | public string path_Images = null;
15 | public string path_Train_Images;
16 | public HTuple path_Preprocessed_Images = new HTuple();
17 | public HTuple hv_Pretrained_DlClassifierName = new HTuple();
18 |
19 |
20 | private System.Threading.Thread _PreprocessThread = null;
21 |
22 | HTuple hv_ImageFiles = new HTuple();
23 | HTuple hv_UniqueClasses = new HTuple();
24 | HTuple hv_GroundTruthLabels = new HTuple();
25 | HTuple hv_LabelsIndices = new HTuple();
26 | HTuple hv_ObjectFilesOut = new HTuple();
27 | HTuple hv_WindowHandle = new HTuple();
28 | HWindowControl hv_HWindowControl = new HWindowControl();
29 |
30 |
31 | public Preprocess()
32 | { }
33 |
34 |
35 | public void PreprocessDlClassifierImagesForTrain(HWindowControl hv_HWindowControl,HTuple hv_Pretrained_DlClassifierName)
36 | {
37 | this.hv_HWindowControl = hv_HWindowControl;
38 | this.hv_WindowHandle = this.hv_HWindowControl.HalconWindow;
39 | this.hv_Pretrained_DlClassifierName = hv_Pretrained_DlClassifierName;
40 |
41 |
42 | hv_ImageFiles.Dispose(); hv_GroundTruthLabels.Dispose(); hv_LabelsIndices.Dispose(); hv_UniqueClasses.Dispose();
43 |
44 | //读取训练数据集,图像Lable为图像所在目录名
45 | read_dl_classifier_data_set(path_Train_Images, "last_folder", out hv_ImageFiles, out hv_GroundTruthLabels, out hv_LabelsIndices, out hv_UniqueClasses);
46 |
47 | //Create the directories for writing the preprocessed images.
48 | CreatePreprocessedImagesFolder();
49 |
50 | //Prepare the new image names.
51 | HTuple hv_BaseNames = new HTuple(); HTuple hv_Extensions = new HTuple(); HTuple hv_Directories = new HTuple();
52 |
53 | hv_BaseNames.Dispose(); hv_Extensions.Dispose(); hv_Directories.Dispose();
54 | parse_filename(hv_ImageFiles, out hv_BaseNames, out hv_Extensions, out hv_Directories);
55 |
56 | hv_ObjectFilesOut.Dispose();
57 | using (HDevDisposeHelper dh = new HDevDisposeHelper())
58 | {
59 | hv_ObjectFilesOut = (((path_Preprocessed_Images + "/") + hv_GroundTruthLabels) + "/") + hv_BaseNames;
60 | }
61 | //
62 | System.Threading.ThreadStart ts = new System.Threading.ThreadStart(ImagePreprocessThreading);
63 | this._PreprocessThread = new System.Threading.Thread(ts);
64 | this._PreprocessThread.IsBackground = true;//设置线程为后台线程
65 | this._PreprocessThread.Start();
66 |
67 | }
68 |
69 | ///
70 | /// 创建预处理图像保存目录
71 | ///
72 | public void CreatePreprocessedImagesFolder()
73 | {
74 |
75 | HOperatorSet.MakeDir(this.path_Preprocessed_Images);
76 |
77 | HTuple hv_path = new HTuple();
78 | for (HTuple hv_I = 0; (int)hv_I <= (int)((new HTuple(hv_UniqueClasses.TupleLength())) - 1); hv_I = (int)hv_I + 1)
79 | {
80 | hv_path.Dispose();
81 | using (HDevDisposeHelper dh = new HDevDisposeHelper())
82 | {
83 | hv_path = (path_Preprocessed_Images + "/") + (hv_UniqueClasses.TupleSelect(hv_I));
84 | }
85 | HOperatorSet.MakeDir(hv_path);
86 | }
87 | }
88 |
89 | ///
90 | /// 批量处理并显示图像线程
91 | ///
92 | private void ImagePreprocessThreading()
93 | {
94 | //Loop through all images,
95 | //preprocess and then write them.
96 | HObject ho_Image = new HObject(); HObject ho_ImagePreprocessed = new HObject();
97 | for (HTuple hv_ImageIndex = 0; (int)hv_ImageIndex <= (hv_ImageFiles.TupleLength() - 1); hv_ImageIndex = (int)hv_ImageIndex + 1)
98 | {
99 | //显示原图像
100 | using (HDevDisposeHelper dh = new HDevDisposeHelper())
101 | {
102 | ho_Image.Dispose();
103 | HOperatorSet.ReadImage(out ho_Image, hv_ImageFiles.TupleSelect(hv_ImageIndex));
104 | DispImageAdaptively(ref hv_HWindowControl, ho_Image);
105 | HOperatorSet.DispText(hv_HWindowControl.HalconWindow, "ImagesPreprocessing:"+hv_ImageIndex, "window", "top", "left", "red", "box", "true");
106 | Console.WriteLine(hv_ImageIndex.ToString());
107 | }
108 | ho_ImagePreprocessed.Dispose();
109 |
110 | //预处理图像
111 | PreprocessImage(this.hv_Pretrained_DlClassifierName,ho_Image, out ho_ImagePreprocessed);
112 |
113 | //保存预处理后图像
114 | using (HDevDisposeHelper dh = new HDevDisposeHelper())
115 | {
116 | HOperatorSet.WriteObject(ho_ImagePreprocessed, hv_ObjectFilesOut.TupleSelect(hv_ImageIndex));
117 | }
118 | }
119 | HOperatorSet.DispText(this.hv_WindowHandle, "Preprocessing over,Click to continue...", "window", "bottom", "right", "red", "box", "false");
120 |
121 | }
122 |
123 | ///
124 | /// 预处理图像用于训练或测试
125 | ///
126 | public void PreprocessImage(string hv_Pretrained_DlClassifierName, HObject ho_Image, out HObject ho_ImagePreprocessed)
127 | {
128 | HTuple hv_DLClassifierHandle = new HTuple();
129 | HOperatorSet.ReadDlClassifier(hv_Pretrained_DlClassifierName, out hv_DLClassifierHandle);
130 | preprocess_dl_classifier_images(ho_Image, out ho_ImagePreprocessed, new HTuple(), new HTuple(), hv_DLClassifierHandle);
131 |
132 | }
133 |
134 | public string GetImagesPaths()
135 | {
136 | StringBuilder sb = new StringBuilder();
137 | if (this.path_Images != null)
138 | {
139 | sb.Append("图像主目录:\r\n").Append(this.path_Images);
140 | sb.Append("\r\n训练图像文件目录:\r\n").Append(this.path_Images + @"\Train_images");
141 | sb.Append("\r\n测试图像文件目录:\r\n").Append(this.path_Images + @"\Test_images");
142 | sb.Append("\r\n预处理图像文件目录:\r\n").Append(this.path_Images + @"\Preprocessed_images");
143 | }
144 | else
145 | {
146 | sb.Append("未选择图像目录,需要点击左下角按钮选择\r\n");
147 | }
148 | return sb.ToString();
149 | }
150 |
151 |
152 | }
153 | }
154 |
--------------------------------------------------------------------------------
/DeepLearning_MNIST/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 | using System.Windows.Forms;
6 |
7 | namespace DeepLearning_MNIST
8 | {
9 | static class Program
10 | {
11 | ///
12 | /// 应用程序的主入口点。
13 | ///
14 | [STAThread]
15 | static void Main()
16 | {
17 | Application.EnableVisualStyles();
18 | Application.SetCompatibleTextRenderingDefault(false);
19 | Application.Run(new Form1());
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/DeepLearning_MNIST/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的一般信息由以下
6 | // 控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("DeepLearning_MNIST")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("DeepLearning_MNIST")]
13 | [assembly: AssemblyCopyright("Copyright © 2019")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | //将 ComVisible 设置为 false 将使此程序集中的类型
18 | //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
19 | //请将此类型的 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("86425a08-efba-44af-aa45-c5f71affb21b")]
24 |
25 | // 程序集的版本信息由下列四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 生成号
30 | // 修订号
31 | //
32 | //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
33 | // 方法是按如下所示使用“*”: :
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/DeepLearning_MNIST/Properties/Resources.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // 此代码由工具生成。
4 | // 运行时版本: 4.0.30319.42000
5 | //
6 | // 对此文件的更改可能导致不正确的行为,如果
7 | // 重新生成代码,则所做更改将丢失。
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace DeepLearning_MNIST.Properties
12 | {
13 |
14 |
15 | ///
16 | /// 强类型资源类,用于查找本地化字符串等。
17 | ///
18 | // 此类是由 StronglyTypedResourceBuilder
19 | // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
20 | // 若要添加或删除成员,请编辑 .ResX 文件,然后重新运行 ResGen
21 | // (以 /str 作为命令选项),或重新生成 VS 项目。
22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
25 | internal class Resources
26 | {
27 |
28 | private static global::System.Resources.ResourceManager resourceMan;
29 |
30 | private static global::System.Globalization.CultureInfo resourceCulture;
31 |
32 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
33 | internal Resources()
34 | {
35 | }
36 |
37 | ///
38 | /// 返回此类使用的缓存 ResourceManager 实例。
39 | ///
40 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
41 | internal static global::System.Resources.ResourceManager ResourceManager
42 | {
43 | get
44 | {
45 | if ((resourceMan == null))
46 | {
47 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DeepLearning_MNIST.Properties.Resources", typeof(Resources).Assembly);
48 | resourceMan = temp;
49 | }
50 | return resourceMan;
51 | }
52 | }
53 |
54 | ///
55 | /// 覆盖当前线程的 CurrentUICulture 属性
56 | /// 使用此强类型的资源类的资源查找。
57 | ///
58 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
59 | internal static global::System.Globalization.CultureInfo Culture
60 | {
61 | get
62 | {
63 | return resourceCulture;
64 | }
65 | set
66 | {
67 | resourceCulture = value;
68 | }
69 | }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/DeepLearning_MNIST/Properties/Resources.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 | text/microsoft-resx
107 |
108 |
109 | 2.0
110 |
111 |
112 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
113 |
114 |
115 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
--------------------------------------------------------------------------------
/DeepLearning_MNIST/Properties/Settings.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // This code was generated by a tool.
4 | // Runtime Version:4.0.30319.42000
5 | //
6 | // Changes to this file may cause incorrect behavior and will be lost if
7 | // the code is regenerated.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace DeepLearning_MNIST.Properties
12 | {
13 |
14 |
15 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
16 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
17 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
18 | {
19 |
20 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
21 |
22 | public static Settings Default
23 | {
24 | get
25 | {
26 | return defaultInstance;
27 | }
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/DeepLearning_MNIST/Properties/Settings.settings:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/DeepLearning_MNIST/Readme.txt:
--------------------------------------------------------------------------------
1 | #DeepLearning_MNIST_Halcon
2 | 欢迎前往论坛地址交流学习https://www.51halcon.com/thread-3881-1-1.html
3 |
4 | 1 预处理图像
5 | 1.1 选择图像目录
6 | 所选目录可以是同时包含训练图像和测试图像的主目录,也可以是训练图像目录或测试图像目录,优先选择主目录.如本例选择mnist_images、Train_images或Test_images目录.如果使用其它图像,需要目录格式与本例一致.
7 |
8 | 1.2 预处理图像
9 | 在进行此步图像预处理时,如果使用其它图像,可以先对图像进行裁剪、旋转、翻转或滤波等普通图像处理,然后再使用深度学习算法处理图像使其能够用于训练.参考Halcon算子描述preprocess_dl_classifier_images.
10 | 预处理后的数据会自动保存在mnist_images\Preprocessed_images文件夹内.如果提示已有预处理好的数据,可以跳过此步直接开始训练,也可以选择删除已有数据重新预处理图像.
11 |
12 | 2 训练分类器
13 | 2.1 参数设置
14 | 建议使用不同参数设置多次进行训练,了解不同参数设置对训练的影响,可以找到更好的训练参数设置.
15 | 注意:BatchSize太大容易导致显存溢出,太小可能不收敛;NumEpochs训练次数越多需要时间越长;LearningRate学习率太大收敛速度快但可能会陷入局部最优,学习率太小收敛速度慢,所需训练次数多;TrainingPercent训练数据太少可能会过拟合;ValidationPercent用于验证的数据比例.
16 | 学习率变化曲线表达公式:LearningRate(Epoch) = InitialLearningRate * Math.Pow(LearningRateStepRatio , Math.Floor(Epoch / LearningRateStepEveryNthEpoch));
17 |
18 | 2.2 训练分类器
19 | 训练过程时间可能较长,需要耐心等待...
20 |
21 | 2.3 保存分类器
22 | 训练完成会自动保存训练模型结果,训练模型默认保存名称为"classifier+图像文件夹名称.hdl",默认保存目录为当前程序运行目录,点击此按钮可以手动另存到其它地方,分类器扩展名应为.hdl
23 |
24 | 2.4 误差分析
25 | 以验证数据集计算训练模型的预测值与实际值得差异,生成混淆矩阵显示.可以分析哪类数据容易被识别错误.
26 |
27 | 3 图像识别测试
28 | 3.1 读取分类器
29 | 如果已有训练好的分类器,可以不进行前面1、2两步,直接读取已训练好的分类器进行测试.如果刚刚完成了分类器训练,此步也可以不操作,程序会默认将前面训练的结果用于测试.
30 |
31 | 3.2 测试分类器
32 | 测试图像可以手动选择新图像测试,也可以随机从测试图片文件夹中自动选择图片;注意,测试图像也需要使用训练模型时相同的深度学习算法处理预处理图像后再测试.
33 |
--------------------------------------------------------------------------------
/DeepLearning_MNIST/Test.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 | using HalconDotNet;
7 |
8 | namespace DeepLearning_MNIST
9 | {
10 | public class Test : HalconTools
11 | {
12 | //测试图像文件路径
13 | public string path_Test_Images;
14 | //测试图像变量
15 | public HObject ho_TestImage = new HObject();
16 | //测试图像文件名
17 | public string ho_TestImageName = null;
18 | //预处理图像变量
19 | public HObject ho_Preprocessed_TestImage = new HObject();
20 | //分类器
21 | public HTuple hv_Test_DlClassifierName = new HTuple();
22 | //用于测试的分类器句柄
23 | public HTuple hv_Test_DLClassifierHandle = new HTuple();
24 | //运行模式 CPU / GPU
25 | private HTuple hv_Runtime = new HTuple();
26 | //预测结果
27 | private HTuple hv_Inference_PredictedClass = new HTuple();
28 | //预测结果可信度
29 | private HTuple hv_Inference_Confidences = new HTuple();
30 |
31 | public Test()
32 | {
33 | hv_Test_DlClassifierName = null;
34 | ho_TestImage = null;
35 | ho_Preprocessed_TestImage = null;
36 | }
37 |
38 |
39 | public void TestImage(ref HWindowControl hv_HWindowControl)
40 | {
41 | if (hv_Test_DlClassifierName == null)
42 | {
43 | Console.WriteLine("错误提示:无可用分类器");
44 | return;
45 | }
46 | if (ho_Preprocessed_TestImage == null)
47 | {
48 | Console.WriteLine("图像未进行预处理");
49 | return;
50 | }
51 |
52 | HObject ho_ImagePreprocessed = new HObject();
53 | HTuple hv_DLClassifierResultHandle = new HTuple();
54 |
55 |
56 | HTuple hv_Exception = new HTuple();
57 | HTuple hv_Text = new HTuple();
58 |
59 | hv_Test_DLClassifierHandle.Dispose();
60 | HOperatorSet.ReadDlClassifier(hv_Test_DlClassifierName, out hv_Test_DLClassifierHandle);
61 |
62 | //If it is not possible to accumulate more than one image at a time the batch size should be set to 1.
63 | HOperatorSet.SetDlClassifierParam(hv_Test_DLClassifierHandle, "batch_size", 1);
64 |
65 | //Set the runtime to 'cpu' to perform the inference on the CPU, if this is possible on the current hardware.
66 | //(see the system requirements in the Installation Guide)
67 | try
68 | {
69 | HOperatorSet.SetDlClassifierParam(hv_Test_DLClassifierHandle, "runtime", "cpu");
70 | hv_Runtime.Dispose();
71 | hv_Runtime = "cpu";
72 | }
73 | // catch (Exception)
74 | catch (HalconException HDevExpDefaultException1)
75 | {
76 | HDevExpDefaultException1.ToHTuple(out hv_Exception);
77 | //Keep the 'gpu' runtime if switching to 'cpu' failed.
78 | hv_Runtime.Dispose();
79 | hv_Runtime = "gpu";
80 | }
81 | //This initializes the runtime environment immediately.
82 | HOperatorSet.SetDlClassifierParam(hv_Test_DLClassifierHandle, "runtime_init", "immediately");
83 | //
84 | //dev_disp_inference_text(hv_Runtime, hv_WindowHandle);
85 | // stop(...); only in hdevelop
86 | ho_ImagePreprocessed.Dispose();
87 |
88 | preprocess_dl_classifier_images(this.ho_TestImage, out ho_ImagePreprocessed, new HTuple(),
89 | new HTuple(), hv_Test_DLClassifierHandle);
90 |
91 | hv_DLClassifierResultHandle.Dispose();
92 | HOperatorSet.ApplyDlClassifier(ho_ImagePreprocessed, hv_Test_DLClassifierHandle,
93 | out hv_DLClassifierResultHandle);
94 | hv_Inference_PredictedClass.Dispose();
95 | HOperatorSet.GetDlClassifierResult(hv_DLClassifierResultHandle, "all", "predicted_classes",
96 | out hv_Inference_PredictedClass);
97 | HOperatorSet.GetDlClassifierResult(hv_DLClassifierResultHandle, "all", "confidences", out hv_Inference_Confidences);
98 | //
99 | DispImageAdaptively(ref hv_HWindowControl, this.ho_TestImage);
100 | hv_Text.Dispose();
101 | using (HDevDisposeHelper dh = new HDevDisposeHelper())
102 | {
103 | hv_Text = "Predicted class: " + hv_Inference_PredictedClass+ "; Confidence: "+ hv_Inference_Confidences;
104 | }
105 | HOperatorSet.DispText(hv_HWindowControl.HalconWindow, hv_Text, "window", "top", "left", "red", "box", "true");
106 |
107 | HOperatorSet.DispText(hv_HWindowControl.HalconWindow, "Click to continue", "window", "bottom", "right", "black", new HTuple(), new HTuple());
108 | this.ho_TestImage = null;
109 | }
110 |
111 | public void RandomGetImage()
112 | {
113 | HTuple hv_TestImageFiles = new HTuple();
114 |
115 |
116 | hv_TestImageFiles.Dispose();
117 | HOperatorSet.ListFiles(this.path_Test_Images, "files", out hv_TestImageFiles);
118 |
119 | //Read / acquire images in a loop and classify them.
120 | using (HDevDisposeHelper dh = new HDevDisposeHelper())
121 | {
122 | ho_TestImageName = hv_TestImageFiles.TupleSelect((new HTuple(HTuple.TupleRand(1) * (new HTuple(hv_TestImageFiles.TupleLength())))).TupleFloor());
123 | }
124 | HOperatorSet.ReadImage(out this.ho_TestImage, ho_TestImageName);
125 | }
126 |
127 | private void DispTestInformation()
128 | {
129 | HTuple hv_Text = new HTuple();
130 | // Initialize local and output iconic variables
131 |
132 | hv_Text.Dispose();
133 | hv_Text = "INFERENCE";
134 | hv_Text[new HTuple(hv_Text.TupleLength())] = "";
135 | hv_Text[new HTuple(hv_Text.TupleLength())] = "This part of the program is a brief introduction on how to ";
136 | hv_Text[new HTuple(hv_Text.TupleLength())] = "make use of your trained classifier. ";
137 | hv_Text[new HTuple(hv_Text.TupleLength())] = "";
138 | hv_Text[new HTuple(hv_Text.TupleLength())] = "It is important that the same preprocessing as for the training ";
139 | hv_Text[new HTuple(hv_Text.TupleLength())] = "of the classifier is applied to the raw images. ";
140 | hv_Text[new HTuple(hv_Text.TupleLength())] = "";
141 | if ((int)(new HTuple(hv_Runtime.TupleEqual("cpu"))) != 0)
142 | {
143 | hv_Text[new HTuple(hv_Text.TupleLength())] = "The 'cpu' runtime has been selected for inference.";
144 | }
145 | }
146 |
147 | }
148 | }
149 |
--------------------------------------------------------------------------------
/DeepLearning_MNIST/Train.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 | using HalconDotNet;
7 | using System.IO;
8 | using System.Threading;
9 |
10 | namespace DeepLearning_MNIST
11 | {
12 | public class Train : HalconTools
13 | {
14 | //常用训练参数
15 | public HTuple hv_BatchSize = new HTuple();
16 | public HTuple hv_NumEpochs = new HTuple();
17 | public HTuple hv_LearningRateStepEveryNthEpoch = new HTuple();
18 | public HTuple hv_LearningRateStepRatio = new HTuple();
19 | public HTuple hv_InitialLearningRate = new HTuple();
20 | public HTuple hv_PlotEveryNthEpoch = new HTuple();
21 | public HTuple hv_TrainingPercent = new HTuple();
22 | public HTuple hv_ValidationPercent = new HTuple();
23 | public HTuple hv_Pretrained_DlClassifierName = new HTuple();
24 |
25 |
26 | //训练后的分类器名称
27 | public HTuple hv_Trained_DlClassifierName = new HTuple();
28 | //训练分类器句柄
29 | public HTuple hv_Train_DLClassifierHandle = new HTuple();
30 | //预处理后图像文件夹
31 | public HTuple hv_PreprocessedFolder = new HTuple();
32 | //训练线程
33 | public Thread _TrainingThread = null;
34 | //窗口句柄
35 | HTuple hv_WindowHandle = new HTuple();
36 |
37 | HTuple hv_ImageFiles = new HTuple(), hv_GroundTruthLabels = new HTuple();
38 | HTuple hv_UniqueClasses = new HTuple();
39 | HTuple hv_I = new HTuple(), hv_path = new HTuple(), hv_BaseNames = new HTuple();
40 | HTuple hv_Extensions = new HTuple(), hv_Directories = new HTuple();
41 | HTuple hv_ObjectFilesOut = new HTuple(), hv_ImageIndex = new HTuple();
42 | HTuple hv_Labels = new HTuple();
43 | HTuple hv_LabelsIndices = new HTuple(), hv_Classes = new HTuple();
44 |
45 | HTuple hv_TrainingImages = new HTuple(), hv_TrainingLabels = new HTuple();
46 | HTuple hv_ValidationImages = new HTuple(), hv_ValidationLabels = new HTuple();
47 | HTuple hv_TestImages = new HTuple(), hv_TestLabels = new HTuple();
48 | HTuple hv_Exception = new HTuple();
49 |
50 | HTuple hv_PredictedClassesValidation = new HTuple();
51 | HTuple hv_ConfusionMatrix = new HTuple(), hv_Runtime = new HTuple();
52 | HTuple hv_TestImageFiles = new HTuple(), hv_Index = new HTuple();
53 | HTuple hv_ImageFile = new HTuple(), hv_DLClassifierResultHandle = new HTuple();
54 | HTuple hv_PredictedClass = new HTuple(), hv_Text = new HTuple();
55 | HTuple hv_RemovePreprocessingAfterExample = new HTuple();
56 |
57 |
58 | public Train()
59 | {
60 | this.hv_Trained_DlClassifierName = null;
61 | this.hv_Train_DLClassifierHandle = null;
62 | this.hv_BatchSize = 32;
63 | this.hv_NumEpochs = 24;
64 | this.hv_LearningRateStepEveryNthEpoch = 6;
65 | this.hv_LearningRateStepRatio = 0.5;
66 | this.hv_InitialLearningRate = 0.001;
67 | this.hv_PlotEveryNthEpoch = 1;
68 | this.hv_TrainingPercent = 60;
69 | this.hv_ValidationPercent = 20;
70 |
71 | }
72 |
73 | public void TrainProcess(HTuple hv_WindowHandle,string pretrained_DlClassifierName)
74 | {
75 | this.hv_WindowHandle = hv_WindowHandle;
76 | //This example shows how to train a deep learning fruit classifier, along with a short overview of the necessary steps.
77 | //
78 | //Initialization.
79 | //dev_open_window_fit_size(0, 0, hv_WindowWidth, hv_WindowHeight, -1, -1, out hv_WindowHandle);
80 | set_display_font(hv_WindowHandle, 16, "mono", "true", "false");
81 | //
82 | //Some procedures use a random number generator. Set the seed for reproducibility.
83 | HOperatorSet.SetSystem("seed_rand", 42);
84 | //
85 | HOperatorSet.ClearWindow(hv_WindowHandle);
86 |
87 | //
88 | //** TRAINING **
89 | //
90 | //Read one of the pretrained networks.
91 | HOperatorSet.ReadDlClassifier(pretrained_DlClassifierName, out this.hv_Train_DLClassifierHandle);
92 |
93 | //2) Split data into training, validation, and test set.
94 | //
95 | //Read the data, i.e., the paths of the images and their respective ground truth labels.
96 | hv_ImageFiles.Dispose(); hv_Labels.Dispose(); hv_LabelsIndices.Dispose(); hv_Classes.Dispose();
97 | read_dl_classifier_data_set(this.hv_PreprocessedFolder, "last_folder", out hv_ImageFiles,
98 | out hv_Labels, out hv_LabelsIndices, out hv_Classes);
99 | //
100 | //Split the data into three subsets,
101 | //Default for training 80%, validation 20%, and testing 0%.
102 | hv_TrainingImages.Dispose(); hv_TrainingLabels.Dispose(); hv_ValidationImages.Dispose(); hv_ValidationLabels.Dispose(); hv_TestImages.Dispose(); hv_TestLabels.Dispose();
103 | split_dl_classifier_data_set(hv_ImageFiles, hv_Labels, this.hv_TrainingPercent,
104 | this.hv_ValidationPercent, out hv_TrainingImages, out hv_TrainingLabels, out hv_ValidationImages,
105 | out hv_ValidationLabels, out hv_TestImages, out hv_TestLabels);
106 | //
107 | //Set training hyper-parameters.
108 | //In order to retrain the neural network, we have to specify
109 | //the class names of our classification problem.
110 | HOperatorSet.SetDlClassifierParam(this.hv_Train_DLClassifierHandle, "classes", hv_Classes);
111 | //Set the batch size.
112 | HOperatorSet.SetDlClassifierParam(this.hv_Train_DLClassifierHandle, "batch_size", this.hv_BatchSize);
113 | hv_RemovePreprocessingAfterExample.Dispose();
114 | hv_RemovePreprocessingAfterExample = 0;
115 | //Try to initialize the runtime environment.
116 | try
117 | {
118 | HOperatorSet.SetDlClassifierParam(this.hv_Train_DLClassifierHandle, "runtime_init",
119 | "immediately");
120 | }
121 | // catch (Exception)
122 | catch (HalconException HDevExpDefaultException1)
123 | {
124 | HDevExpDefaultException1.ToHTuple(out hv_Exception);
125 | HOperatorSet.DispText(hv_WindowHandle, "Failed to initialize the runtime environment.", "window", "bottom", "right", "red", "box", "false");
126 | //dev_disp_error_text(hv_Exception);
127 | if ((int)(hv_RemovePreprocessingAfterExample.TupleAnd(new HTuple(((hv_Exception.TupleSelect(
128 | 0))).TupleNotEqual(4104)))) != 0)
129 | {
130 | remove_dir_recursively(hv_PreprocessedFolder);
131 | using (HDevDisposeHelper dh = new HDevDisposeHelper())
132 | {
133 | HOperatorSet.DispText(hv_WindowHandle, ("Preprocessed data in folder \"" + hv_PreprocessedFolder) + "\" have been deleted.",
134 | "window", "top", "right", "red", new HTuple(), new HTuple());
135 | }
136 | }
137 | return;
138 | }
139 | //For this data set, an initial learning rate of 0.001 has proven to yield good results.
140 | HOperatorSet.SetDlClassifierParam(this.hv_Train_DLClassifierHandle, "learning_rate", this.hv_InitialLearningRate);
141 |
142 | // stop(...); only in hdevelop
143 | //
144 | //Train the classifier.
145 | HOperatorSet.DispText(hv_WindowHandle, "Training has started...",
146 | "window", "top", "left", "black", new HTuple(), new HTuple());
147 |
148 | Console.WriteLine("开始训练过程...");
149 |
150 | _TrainingThread = new Thread(new ThreadStart(TrainingThread));
151 | _TrainingThread.IsBackground = true;
152 | _TrainingThread.Start();
153 | //
154 | //In this example, we reduce the learning rate by a factor of 1/10 every 5th epoch.
155 | //We iterate 50 times over the full training set.
156 |
157 |
158 | //ComputeConfusionMatrix(hv_WindowHandle);
159 | }
160 |
161 | public void ComputeConfusionMatrix(HTuple hv_WindowHandle)
162 | {
163 | HOperatorSet.ClearWindow(hv_WindowHandle);
164 | hv_Train_DLClassifierHandle.Dispose();
165 | HOperatorSet.ReadDlClassifier(this.hv_Trained_DlClassifierName, out hv_Train_DLClassifierHandle);
166 | //
167 | //Compute the confusion matrix for the validation data set.
168 | hv_PredictedClassesValidation.Dispose();
169 | get_predicted_classes(hv_ValidationImages, hv_Train_DLClassifierHandle, out hv_PredictedClassesValidation);
170 | hv_ConfusionMatrix.Dispose();
171 | gen_confusion_matrix(hv_ValidationLabels, hv_PredictedClassesValidation, new HTuple(),
172 | new HTuple(), hv_WindowHandle, out hv_ConfusionMatrix);
173 |
174 | HOperatorSet.DispText(hv_WindowHandle, "Validation data", "window",
175 | "top", "left", "gray", "box", "false");
176 | HOperatorSet.DispText(hv_WindowHandle, "Click to continue...",
177 | "window", "bottom", "right", "black", new HTuple(), new HTuple());
178 |
179 | }
180 |
181 | private void TrainingThread()
182 | {
183 | train_classifier(this.hv_Train_DLClassifierHandle, this.hv_Trained_DlClassifierName, this.hv_NumEpochs, hv_TrainingImages,
184 | hv_TrainingLabels, hv_ValidationImages, hv_ValidationLabels, this.hv_LearningRateStepEveryNthEpoch,
185 | this.hv_LearningRateStepRatio, this.hv_PlotEveryNthEpoch, this.hv_WindowHandle);
186 | HOperatorSet.DispText(this.hv_WindowHandle, "Training over, Click to continue...",
187 | "window", "bottom", "right", "black", new HTuple(), new HTuple());
188 | }
189 |
190 | public string TrainClassifierParams()
191 | {
192 | string[] classifierParamsLabels = { "BatchSize", "NumEpochs", "InitialLearningRate", "LearningRateStepRatio", "LearningRateStepEveryNthEpoch", "TrainingPercent", "ValidationPercent" };
193 | string[] classifierParamsValues = { this.hv_BatchSize.ToString(), this.hv_NumEpochs.ToString(), this.hv_InitialLearningRate.ToString(), this.hv_LearningRateStepRatio.ToString(), this.hv_LearningRateStepEveryNthEpoch.ToString(), this.hv_TrainingPercent.ToString(), this.hv_ValidationPercent.ToString() };
194 |
195 | StringBuilder classifierParams = new StringBuilder();
196 | for (int i = 0; i < classifierParamsLabels.Length; i++)
197 | {
198 | classifierParams.Append(classifierParamsLabels[i] + ":" + classifierParamsValues[i] + "\r\n");
199 | }
200 | return classifierParams.ToString();
201 |
202 | }
203 |
204 | private void train_classifier(HTuple hv_DLClassifierHandle, HTuple hv_FileName,
205 | HTuple hv_NumEpochs, HTuple hv_TrainingImages, HTuple hv_TrainingLabels, HTuple hv_ValidationImages,
206 | HTuple hv_ValidationLabels, HTuple hv_LearningRateStepEveryNthEpoch, HTuple hv_LearningRateStepRatio,
207 | HTuple hv_PlotEveryNthEpoch, HTuple hv_WindowHandle)
208 | {
209 |
210 | // Stack for temporary objects
211 | HObject[] OTemp = new HObject[20];
212 |
213 | // Local iconic variables
214 |
215 | HObject ho_BatchImages = null;
216 |
217 | // Local control variables
218 |
219 | HTuple hv_TrainingErrors = new HTuple(), hv_ValidationErrors = new HTuple();
220 | HTuple hv_LearningRates = new HTuple(), hv_Epochs = new HTuple();
221 | HTuple hv_LossByIteration = new HTuple(), hv_BatchSize = new HTuple();
222 | HTuple hv_MinValidationError = new HTuple(), hv_NumBatchesInEpoch = new HTuple();
223 | HTuple hv_NumTotalIterations = new HTuple(), hv_PlottedIterations = new HTuple();
224 | HTuple hv_TrainSequence = new HTuple(), hv_SelectPercentageTrainingImages = new HTuple();
225 | HTuple hv_TrainingImagesSelected = new HTuple(), hv_TrainingLabelsSelected = new HTuple();
226 | HTuple hv_Epoch = new HTuple(), hv_Iteration = new HTuple();
227 | HTuple hv_BatchStart = new HTuple(), hv_BatchEnd = new HTuple();
228 | HTuple hv_BatchIndices = new HTuple(), hv_BatchImageFiles = new HTuple();
229 | HTuple hv_BatchLabels = new HTuple(), hv_GenParamName = new HTuple();
230 | HTuple hv_GenParamValue = new HTuple(), hv_DLClassifierTrainResultHandle = new HTuple();
231 | HTuple hv_Loss = new HTuple(), hv_CurrentIteration = new HTuple();
232 | HTuple hv_TrainingDLClassifierResultIDs = new HTuple();
233 | HTuple hv_ValidationDLClassifierResultIDs = new HTuple();
234 | HTuple hv_TrainingTop1Error = new HTuple(), hv_ValidationTop1Error = new HTuple();
235 | HTuple hv_LearningRate = new HTuple();
236 |
237 | HTupleVector hvec_TrainingPredictedLabels = new HTupleVector(1);
238 | HTupleVector hvec_TrainingConfidences = new HTupleVector(1);
239 | HTupleVector hvec_ValidationPredictedLabels = new HTupleVector(1);
240 | HTupleVector hvec_ValidationConfidences = new HTupleVector(1);
241 | // Initialize local and output iconic variables
242 | HOperatorSet.GenEmptyObj(out ho_BatchImages);
243 | try
244 | {
245 | //For the plot during training,
246 | //we need to concatenate some intermediate results.
247 | hv_TrainingErrors.Dispose();
248 | hv_TrainingErrors = new HTuple();
249 | hv_ValidationErrors.Dispose();
250 | hv_ValidationErrors = new HTuple();
251 | hv_LearningRates.Dispose();
252 | hv_LearningRates = new HTuple();
253 | hv_Epochs.Dispose();
254 | hv_Epochs = new HTuple();
255 | hv_LossByIteration.Dispose();
256 | hv_LossByIteration = new HTuple();
257 | hv_BatchSize.Dispose();
258 | HOperatorSet.GetDlClassifierParam(hv_DLClassifierHandle, "batch_size", out hv_BatchSize);
259 | hv_MinValidationError.Dispose();
260 | hv_MinValidationError = 1;
261 | //
262 | //Create a tuple that includes all the iterations
263 | //where the plot should be computed (including the last ieration).
264 | hv_NumBatchesInEpoch.Dispose();
265 | using (HDevDisposeHelper dh = new HDevDisposeHelper())
266 | {
267 | hv_NumBatchesInEpoch = (((((new HTuple(hv_TrainingImages.TupleLength()
268 | )) / (hv_BatchSize.TupleReal()))).TupleFloor())).TupleInt();
269 | }
270 | hv_NumTotalIterations.Dispose();
271 | using (HDevDisposeHelper dh = new HDevDisposeHelper())
272 | {
273 | hv_NumTotalIterations = (hv_NumBatchesInEpoch * hv_NumEpochs) - 1;
274 | }
275 | hv_PlottedIterations.Dispose();
276 | using (HDevDisposeHelper dh = new HDevDisposeHelper())
277 | {
278 | hv_PlottedIterations = ((((hv_NumBatchesInEpoch * HTuple.TupleGenSequence(
279 | 0, hv_NumEpochs - 1, hv_PlotEveryNthEpoch))).TupleConcat(hv_NumTotalIterations))).TupleRound()
280 | ;
281 | }
282 | //
283 | //TrainSequence is used for easier indexing of the training data.
284 | using (HDevDisposeHelper dh = new HDevDisposeHelper())
285 | {
286 | hv_TrainSequence.Dispose();
287 | HOperatorSet.TupleGenSequence(0, (new HTuple(hv_TrainingImages.TupleLength()
288 | )) - 1, 1, out hv_TrainSequence);
289 | }
290 | //
291 | //Select a subset of the training data set
292 | //in order to obtain a fast approximation
293 | //of the training error during training (plotting).
294 | hv_SelectPercentageTrainingImages.Dispose();
295 | hv_SelectPercentageTrainingImages = 100;
296 | hv_TrainingImagesSelected.Dispose(); hv_TrainingLabelsSelected.Dispose();
297 | select_percentage_dl_classifier_data(hv_TrainingImages, hv_TrainingLabels,
298 | hv_SelectPercentageTrainingImages, out hv_TrainingImagesSelected, out hv_TrainingLabelsSelected);
299 | //
300 | HTuple end_val25 = hv_NumEpochs - 1;
301 | HTuple step_val25 = 1;
302 | #region
303 | for (hv_Epoch = 0; hv_Epoch.Continue(end_val25, step_val25); hv_Epoch = hv_Epoch.TupleAdd(step_val25))
304 | {
305 | //In order to get randomness in each epoch,
306 | //the training set is shuffled every epoch.
307 | {
308 | HTuple ExpTmpOutVar_0;
309 | tuple_shuffle(hv_TrainSequence, out ExpTmpOutVar_0);
310 | hv_TrainSequence.Dispose();
311 | hv_TrainSequence = ExpTmpOutVar_0;
312 | }
313 | HTuple end_val29 = hv_NumBatchesInEpoch - 1;
314 | HTuple step_val29 = 1;
315 | for (hv_Iteration = 0; hv_Iteration.Continue(end_val29, step_val29); hv_Iteration = hv_Iteration.TupleAdd(step_val29))
316 | {
317 | //Select a batch from the training data set.
318 | hv_BatchStart.Dispose();
319 | using (HDevDisposeHelper dh = new HDevDisposeHelper())
320 | {
321 | hv_BatchStart = hv_Iteration * hv_BatchSize;
322 | }
323 | hv_BatchEnd.Dispose();
324 | using (HDevDisposeHelper dh = new HDevDisposeHelper())
325 | {
326 | hv_BatchEnd = hv_BatchStart + (hv_BatchSize - 1);
327 | }
328 | hv_BatchIndices.Dispose();
329 | using (HDevDisposeHelper dh = new HDevDisposeHelper())
330 | {
331 | hv_BatchIndices = hv_TrainSequence.TupleSelectRange(
332 | hv_BatchStart, hv_BatchEnd);
333 | }
334 | hv_BatchImageFiles.Dispose();
335 | using (HDevDisposeHelper dh = new HDevDisposeHelper())
336 | {
337 | hv_BatchImageFiles = hv_TrainingImages.TupleSelect(
338 | hv_BatchIndices);
339 | }
340 | hv_BatchLabels.Dispose();
341 | using (HDevDisposeHelper dh = new HDevDisposeHelper())
342 | {
343 | hv_BatchLabels = hv_TrainingLabels.TupleSelect(
344 | hv_BatchIndices);
345 | }
346 | //
347 | //Read the image of the current batch.
348 | ho_BatchImages.Dispose();
349 | HOperatorSet.ReadImage(out ho_BatchImages, hv_BatchImageFiles);
350 | //Augment the images to get a better variety of training images.
351 | hv_GenParamName.Dispose();
352 | hv_GenParamName = "mirror";
353 | hv_GenParamValue.Dispose();
354 | hv_GenParamValue = "rc";
355 | {
356 | HObject ExpTmpOutVar_0;
357 | augment_images(ho_BatchImages, out ExpTmpOutVar_0, hv_GenParamName, hv_GenParamValue);
358 | ho_BatchImages.Dispose();
359 | ho_BatchImages = ExpTmpOutVar_0;
360 | }
361 | //
362 | //Train the network with these images and ground truth labels.
363 | hv_DLClassifierTrainResultHandle.Dispose();
364 | HOperatorSet.TrainDlClassifierBatch(ho_BatchImages, hv_DLClassifierHandle,
365 | hv_BatchLabels, out hv_DLClassifierTrainResultHandle);
366 | //You can access the current value of the loss function,
367 | //which should decrease during the training.
368 | hv_Loss.Dispose();
369 | HOperatorSet.GetDlClassifierTrainResult(hv_DLClassifierTrainResultHandle,
370 | "loss", out hv_Loss);
371 | //Store the loss in a tuple .
372 | using (HDevDisposeHelper dh = new HDevDisposeHelper())
373 | {
374 | {
375 | HTuple
376 | ExpTmpLocalVar_LossByIteration = hv_LossByIteration.TupleConcat(
377 | hv_Loss);
378 | hv_LossByIteration.Dispose();
379 | hv_LossByIteration = ExpTmpLocalVar_LossByIteration;
380 | }
381 | }
382 | //
383 | //In regular intervals, we want to evaluate
384 | //how well our classifier performs.
385 | hv_CurrentIteration.Dispose();
386 | using (HDevDisposeHelper dh = new HDevDisposeHelper())
387 | {
388 | hv_CurrentIteration = ((hv_Iteration + (hv_NumBatchesInEpoch * hv_Epoch))).TupleInt()
389 | ;
390 | }
391 | if ((int)(((hv_CurrentIteration.TupleEqualElem(hv_PlottedIterations))).TupleSum()
392 | ) != 0)
393 | {
394 | //Plot the progress regularly.
395 | //Evaluate the current classifier on the training and validation set.
396 | hv_TrainingDLClassifierResultIDs.Dispose(); hvec_TrainingPredictedLabels.Dispose(); hvec_TrainingConfidences.Dispose();
397 | apply_dl_classifier_batchwise(hv_TrainingImagesSelected, hv_DLClassifierHandle,
398 | out hv_TrainingDLClassifierResultIDs, out hvec_TrainingPredictedLabels,
399 | out hvec_TrainingConfidences);
400 | hv_ValidationDLClassifierResultIDs.Dispose(); hvec_ValidationPredictedLabels.Dispose(); hvec_ValidationConfidences.Dispose();
401 | apply_dl_classifier_batchwise(hv_ValidationImages, hv_DLClassifierHandle,
402 | out hv_ValidationDLClassifierResultIDs, out hvec_ValidationPredictedLabels,
403 | out hvec_ValidationConfidences);
404 | //Evaluate the top-1 error on each dataset.
405 | hv_TrainingTop1Error.Dispose();
406 | evaluate_dl_classifier(hv_TrainingLabelsSelected, hv_DLClassifierHandle,
407 | hv_TrainingDLClassifierResultIDs, "top1_error", "global", out hv_TrainingTop1Error);
408 | hv_ValidationTop1Error.Dispose();
409 | evaluate_dl_classifier(hv_ValidationLabels, hv_DLClassifierHandle, hv_ValidationDLClassifierResultIDs,
410 | "top1_error", "global", out hv_ValidationTop1Error);
411 | //Concatenate the values for the plot.
412 | hv_LearningRate.Dispose();
413 | HOperatorSet.GetDlClassifierParam(hv_DLClassifierHandle, "learning_rate",
414 | out hv_LearningRate);
415 | using (HDevDisposeHelper dh = new HDevDisposeHelper())
416 | {
417 | {
418 | HTuple
419 | ExpTmpLocalVar_TrainingErrors = hv_TrainingErrors.TupleConcat(
420 | hv_TrainingTop1Error);
421 | hv_TrainingErrors.Dispose();
422 | hv_TrainingErrors = ExpTmpLocalVar_TrainingErrors;
423 | }
424 | }
425 | using (HDevDisposeHelper dh = new HDevDisposeHelper())
426 | {
427 | {
428 | HTuple
429 | ExpTmpLocalVar_ValidationErrors = hv_ValidationErrors.TupleConcat(
430 | hv_ValidationTop1Error);
431 | hv_ValidationErrors.Dispose();
432 | hv_ValidationErrors = ExpTmpLocalVar_ValidationErrors;
433 | }
434 | }
435 | using (HDevDisposeHelper dh = new HDevDisposeHelper())
436 | {
437 | {
438 | HTuple
439 | ExpTmpLocalVar_LearningRates = hv_LearningRates.TupleConcat(
440 | hv_LearningRate);
441 | hv_LearningRates.Dispose();
442 | hv_LearningRates = ExpTmpLocalVar_LearningRates;
443 | }
444 | }
445 | using (HDevDisposeHelper dh = new HDevDisposeHelper())
446 | {
447 | {
448 | HTuple
449 | ExpTmpLocalVar_Epochs = hv_Epochs.TupleConcat(
450 | (hv_PlottedIterations.TupleSelect(new HTuple(hv_Epochs.TupleLength()
451 | ))) / (hv_NumBatchesInEpoch.TupleReal()));
452 | hv_Epochs.Dispose();
453 | hv_Epochs = ExpTmpLocalVar_Epochs;
454 | }
455 | }
456 |
457 | //Plot validation and error against the epochs in order to
458 | //observe the progress of the training.
459 | plot_dl_classifier_training_progress(hv_TrainingErrors, hv_ValidationErrors,hv_LearningRates, hv_Epochs, hv_NumEpochs, hv_WindowHandle);
460 | //如果上面绘制坐标系到窗体过程报错,搞不定的话就用下面这句代替,直接显示训练数据到窗体
461 | //disp_training_progress_datas(hv_TrainingErrors, hv_ValidationErrors, hv_LearningRates, hv_Epochs, hv_NumEpochs, hv_WindowHandle);
462 |
463 |
464 | if ((int)(new HTuple(hv_ValidationTop1Error.TupleLessEqual(hv_MinValidationError))) != 0)
465 | {
466 | HOperatorSet.WriteDlClassifier(hv_DLClassifierHandle, hv_FileName);
467 | hv_MinValidationError.Dispose();
468 | hv_MinValidationError = new HTuple(hv_ValidationTop1Error);
469 | }
470 | }
471 | }
472 | //Reduce the learning rate every nth epoch.
473 | if ((int)(new HTuple((((hv_Epoch + 1) % hv_LearningRateStepEveryNthEpoch)).TupleEqual(
474 | 0))) != 0)
475 | {
476 | using (HDevDisposeHelper dh = new HDevDisposeHelper())
477 | {
478 | HOperatorSet.SetDlClassifierParam(hv_DLClassifierHandle, "learning_rate",
479 | hv_LearningRate * hv_LearningRateStepRatio);
480 | }
481 | hv_LearningRate.Dispose();
482 | HOperatorSet.GetDlClassifierParam(hv_DLClassifierHandle, "learning_rate",
483 | out hv_LearningRate);
484 | }
485 | }
486 | #endregion
487 | // stop(...); only in hdevelop
488 | ho_BatchImages.Dispose();
489 |
490 | hv_TrainingErrors.Dispose();
491 | hv_ValidationErrors.Dispose();
492 | hv_LearningRates.Dispose();
493 | hv_Epochs.Dispose();
494 | hv_LossByIteration.Dispose();
495 | hv_BatchSize.Dispose();
496 | hv_MinValidationError.Dispose();
497 | hv_NumBatchesInEpoch.Dispose();
498 | hv_NumTotalIterations.Dispose();
499 | hv_PlottedIterations.Dispose();
500 | hv_TrainSequence.Dispose();
501 | hv_SelectPercentageTrainingImages.Dispose();
502 | hv_TrainingImagesSelected.Dispose();
503 | hv_TrainingLabelsSelected.Dispose();
504 | hv_Epoch.Dispose();
505 | hv_Iteration.Dispose();
506 | hv_BatchStart.Dispose();
507 | hv_BatchEnd.Dispose();
508 | hv_BatchIndices.Dispose();
509 | hv_BatchImageFiles.Dispose();
510 | hv_BatchLabels.Dispose();
511 | hv_GenParamName.Dispose();
512 | hv_GenParamValue.Dispose();
513 | hv_DLClassifierTrainResultHandle.Dispose();
514 | hv_Loss.Dispose();
515 | hv_CurrentIteration.Dispose();
516 | hv_TrainingDLClassifierResultIDs.Dispose();
517 | hv_ValidationDLClassifierResultIDs.Dispose();
518 | hv_TrainingTop1Error.Dispose();
519 | hv_ValidationTop1Error.Dispose();
520 | hv_LearningRate.Dispose();
521 | hvec_TrainingPredictedLabels.Dispose();
522 | hvec_TrainingConfidences.Dispose();
523 | hvec_ValidationPredictedLabels.Dispose();
524 | hvec_ValidationConfidences.Dispose();
525 |
526 | return;
527 | }
528 | catch (HalconException HDevExpDefaultException)
529 | {
530 | ho_BatchImages.Dispose();
531 |
532 | hv_TrainingErrors.Dispose();
533 | hv_ValidationErrors.Dispose();
534 | hv_LearningRates.Dispose();
535 | hv_Epochs.Dispose();
536 | hv_LossByIteration.Dispose();
537 | hv_BatchSize.Dispose();
538 | hv_MinValidationError.Dispose();
539 | hv_NumBatchesInEpoch.Dispose();
540 | hv_NumTotalIterations.Dispose();
541 | hv_PlottedIterations.Dispose();
542 | hv_TrainSequence.Dispose();
543 | hv_SelectPercentageTrainingImages.Dispose();
544 | hv_TrainingImagesSelected.Dispose();
545 | hv_TrainingLabelsSelected.Dispose();
546 | hv_Epoch.Dispose();
547 | hv_Iteration.Dispose();
548 | hv_BatchStart.Dispose();
549 | hv_BatchEnd.Dispose();
550 | hv_BatchIndices.Dispose();
551 | hv_BatchImageFiles.Dispose();
552 | hv_BatchLabels.Dispose();
553 | hv_GenParamName.Dispose();
554 | hv_GenParamValue.Dispose();
555 | hv_DLClassifierTrainResultHandle.Dispose();
556 | hv_Loss.Dispose();
557 | hv_CurrentIteration.Dispose();
558 | hv_TrainingDLClassifierResultIDs.Dispose();
559 | hv_ValidationDLClassifierResultIDs.Dispose();
560 | hv_TrainingTop1Error.Dispose();
561 | hv_ValidationTop1Error.Dispose();
562 | hv_LearningRate.Dispose();
563 | hvec_TrainingPredictedLabels.Dispose();
564 | hvec_TrainingConfidences.Dispose();
565 | hvec_ValidationPredictedLabels.Dispose();
566 | hvec_ValidationConfidences.Dispose();
567 |
568 | throw HDevExpDefaultException;
569 | }
570 |
571 | }
572 |
573 | private void disp_training_progress_datas(HTuple hv_TrainingErrors, HTuple hv_ValidationErrors, HTuple hv_LearningRates, HTuple hv_Epochs, HTuple hv_NumEpochs, HTuple hv_WindowHandle)
574 | {
575 | HOperatorSet.ClearWindow(hv_WindowHandle);
576 |
577 | if (hv_Epochs.TupleMax()< hv_NumEpochs)
578 | {
579 | HOperatorSet.DispText(hv_WindowHandle, "Training...","window", "top", "left", "black", new HTuple(), new HTuple());
580 | }
581 | HOperatorSet.DispText(hv_WindowHandle, "hv_Epoch", "window", 80, 30, "white", "box", "false");
582 | HOperatorSet.DispText(hv_WindowHandle, "LearningRate", "window", 80, 150, "white", "box", "false");
583 | HOperatorSet.DispText(hv_WindowHandle, "TrainingError", "window", 80, 300, "white", "box", "false");
584 | HOperatorSet.DispText(hv_WindowHandle, "ValidationError", "window", 80, 460, "white", "box", "false");
585 |
586 | HOperatorSet.DispText(hv_WindowHandle, hv_Epochs.TupleString(".0f"), "window", 100, 30, "white", "box", "false");
587 | HOperatorSet.DispText(hv_WindowHandle, hv_LearningRates.TupleString(".8f"), "window", 100, 150, "white", "box", "false");
588 | HOperatorSet.DispText(hv_WindowHandle, (hv_TrainingErrors * 100).TupleString(".2f") + "%", "window", 100, 300, "white", "box", "false");
589 | HOperatorSet.DispText(hv_WindowHandle, (hv_ValidationErrors * 100).TupleString(".2f") + "%", "window", 100, 460, "white", "box", "false");
590 | }
591 | }
592 | }
593 |
--------------------------------------------------------------------------------
/Readme.txt:
--------------------------------------------------------------------------------
1 | #DeepLearning_MNIST 本资源用于交流学习,完全免费分享,论坛地址https://www.51halcon.com/thread-3881-1-1.html
2 | 本例基于Halcon深度学习,需要安装Halcon深度学习环境,参考https://blog.csdn.net/xuanbi8560/article/details/80911015
3 |
4 | 1 预处理图像
5 | 1.1 选择图像目录
6 | 所选目录可以是同时包含训练图像和测试图像的主目录,也可以是训练图像目录或测试图像目录,优先选择主目录.如本例选择mnist_images、Train_images或Test_images目录.如果使用其它图像,需要目录格式与本例一致.
7 |
8 | 1.2 预处理图像
9 | 在进行此步图像预处理时,如果使用其它图像,可以先对图像进行裁剪、旋转、翻转或滤波等普通图像处理,然后再使用深度学习算法处理图像使其能够用于训练.参考Halcon算子描述preprocess_dl_classifier_images.
10 | 预处理后的数据会自动保存在mnist_images\Preprocessed_images文件夹内.如果提示已有预处理好的数据,可以跳过此步直接开始训练,也可以选择删除已有数据重新预处理图像.
11 |
12 | 2 训练分类器
13 | 2.1 参数设置
14 | 建议使用不同参数设置多次进行训练,了解不同参数设置对训练的影响,可以找到更好的训练参数设置.
15 | 注意:BatchSize太大容易导致显存溢出,太小可能不收敛;NumEpochs训练次数越多需要时间越长;LearningRate学习率太大收敛速度快但可能会陷入局部最优,学习率太小收敛速度慢,所需训练次数多;TrainingPercent训练数据太少可能会过拟合;ValidationPercent用于验证的数据比例.
16 | 学习率变化曲线表达公式:LearningRate(Epoch) = InitialLearningRate * Math.Pow(LearningRateStepRatio , Math.Floor(Epoch / LearningRateStepEveryNthEpoch));
17 |
18 | 2.2 训练分类器
19 | 训练过程时间可能较长,需要耐心等待...
20 |
21 | 2.3 保存分类器
22 | 训练完成会自动保存训练模型结果,训练模型默认保存名称为"classifier+图像文件夹名称.hdl",默认保存目录为当前程序运行目录,点击此按钮可以手动另存到其它地方,分类器扩展名应为.hdl
23 |
24 | 2.4 误差分析
25 | 以验证数据集计算训练模型的预测值与实际值得差异,生成混淆矩阵显示.可以分析哪类数据容易被识别错误.
26 |
27 | 3 图像识别测试
28 | 3.1 读取分类器
29 | 如果已有训练好的分类器,可以不进行前面1、2两步,直接读取已训练好的分类器进行测试.如果刚刚完成了分类器训练,此步也可以不操作,程序会默认将前面训练的结果用于测试.
30 |
31 | 3.2 测试分类器
32 | 测试图像可以手动选择新图像测试,也可以随机从测试图片文件夹中自动选择图片;注意,测试图像也需要使用训练模型时相同的深度学习算法处理预处理图像后再测试.
33 |
--------------------------------------------------------------------------------
/mnist_images.rar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/675491918/DeepLearning_MNIST_Halcon/1df9fc5096c31724f9705937ce5170dce9cf1a19/mnist_images.rar
--------------------------------------------------------------------------------
/screenshot (1).png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/675491918/DeepLearning_MNIST_Halcon/1df9fc5096c31724f9705937ce5170dce9cf1a19/screenshot (1).png
--------------------------------------------------------------------------------
/screenshot (2).png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/675491918/DeepLearning_MNIST_Halcon/1df9fc5096c31724f9705937ce5170dce9cf1a19/screenshot (2).png
--------------------------------------------------------------------------------
/screenshot (3).png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/675491918/DeepLearning_MNIST_Halcon/1df9fc5096c31724f9705937ce5170dce9cf1a19/screenshot (3).png
--------------------------------------------------------------------------------