-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecognizer.cs
More file actions
99 lines (84 loc) · 2.67 KB
/
Recognizer.cs
File metadata and controls
99 lines (84 loc) · 2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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
using Newtonsoft.Json;
using SimpleEngine;
using TensorFlow;
namespace PaintAI
{
internal class Recognizer
{
private TFGraph graph;
private TFSession session;
private Label[] outputLabels;
private PictureBoxRenderer boxRenderer;
private Task<int[]> thread;
private bool loaded;
private bool recognizing;
public Recognizer(PictureBoxRenderer boxRenderer, Label[] outputLabels)
{
this.outputLabels = outputLabels;
this.boxRenderer = boxRenderer;
LoadModel();
}
~Recognizer()
{
Dispose();
}
public void Dispose()
{
session.Dispose();
graph.Dispose();
}
private void LoadModel()
{
if (loaded)
{
return;
}
// Load model
loaded = true;
byte[] buffer = File.ReadAllBytes("C:\\Users\\super\\Desktop\\Code\\C# Projects\\SimpleGFX\\PaintAI\\Mnist_model_98.5success.pb");
graph = new TFGraph();
graph.Import(buffer);
session = new TFSession(graph);
outputLabels[0].Text = "Model loaded";
}
private int[] RecognizeImage()
{
var runner = session.GetRunner();
var bitmap = boxRenderer.GetBitmap().ToTensorFormat();
var tensor = Utils.BitmapToTensorGrayScale(bitmap);
runner.AddInput(graph["conv1_input"][0], tensor);
runner.Fetch(graph["activation_4/Softmax"][0]);
var output = runner.Run();
var vecResults = output[0].GetValue();
float[,] results = (float[,])vecResults;
// Evaluate the results
// int max_result = Utils.GetIntegerFromQuantized(quantized);
int[] int_results = Utils.GetSortedResults(results);
tensor.Dispose();
bitmap.Dispose();
return int_results;
}
public void RecognizeImageAsync()
{
if (thread != null)
{
if (!thread.IsCompleted)
{
return;
}
DisplayResults(thread.Result);
}
thread = new Task<int[]>(RecognizeImage);
thread.Start();
}
public void DisplayResults(int[] results)
{
int minIndex = Math.Min(results.Length, outputLabels.Length);
for (int i = 0; i < minIndex; i++)
{
string result = results[i].ToString();
outputLabels[i].Text = result;
}
}
}
}