-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdigit_recognition.js
336 lines (287 loc) · 7.96 KB
/
digit_recognition.js
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
//-------------------
// GLOBAL variables
//-------------------
let model;
var canvasSize = 150;
var canvasStrokeStyle = "white";
var canvasLineJoin = "round";
var canvasLineWidth = 5;
var canvasBackgroundColor = "black";
var canvasId = "canvas";
var clickX = new Array();
var clickY = new Array();
var clickD = new Array();
var drawing;
//---------------
// Create canvas
//---------------
var canvasBox = document.getElementById('canvas_box');
var canvas = document.createElement("canvas");
canvas.setAttribute("width", canvasSize);
canvas.setAttribute("height", canvasSize);
canvas.setAttribute("id", canvasId);
canvas.style.backgroundColor = canvasBackgroundColor;
canvasBox.appendChild(canvas);
if(typeof G_vmlCanvasManager != 'undefined') {
canvas = G_vmlCanvasManager.initElement(canvas);
}
ctx = canvas.getContext("2d");
//---------------------
// MOUSE DOWN function
//---------------------
$("#canvas").mousedown(function(e) {
var rect = canvas.getBoundingClientRect();
var mouseX = e.clientX- rect.left;;
var mouseY = e.clientY- rect.top;
drawing = true;
addUserGesture(mouseX, mouseY);
drawOnCanvas();
});
//-----------------------
// TOUCH START function
//-----------------------
canvas.addEventListener("touchstart", function (e) {
if (e.target == canvas) {
e.preventDefault();
}
var rect = canvas.getBoundingClientRect();
var touch = e.touches[0];
var mouseX = touch.clientX - rect.left;
var mouseY = touch.clientY - rect.top;
drawing = true;
addUserGesture(mouseX, mouseY);
drawOnCanvas();
}, false);
//---------------------
// MOUSE MOVE function
//---------------------
$("#canvas").mousemove(function(e) {
if(drawing) {
var rect = canvas.getBoundingClientRect();
var mouseX = e.clientX- rect.left;;
var mouseY = e.clientY- rect.top;
addUserGesture(mouseX, mouseY, true);
drawOnCanvas();
}
});
//---------------------
// TOUCH MOVE function
//---------------------
canvas.addEventListener("touchmove", function (e) {
if (e.target == canvas) {
e.preventDefault();
}
if(drawing) {
var rect = canvas.getBoundingClientRect();
var touch = e.touches[0];
var mouseX = touch.clientX - rect.left;
var mouseY = touch.clientY - rect.top;
addUserGesture(mouseX, mouseY, true);
drawOnCanvas();
}
}, false);
//-------------------
// MOUSE UP function
//-------------------
$("#canvas").mouseup(function(e) {
drawing = false;
});
//---------------------
// TOUCH END function
//---------------------
canvas.addEventListener("touchend", function (e) {
if (e.target == canvas) {
e.preventDefault();
}
drawing = false;
}, false);
//----------------------
// MOUSE LEAVE function
//----------------------
$("#canvas").mouseleave(function(e) {
drawing = false;
});
//-----------------------
// TOUCH LEAVE function
//-----------------------
canvas.addEventListener("touchleave", function (e) {
if (e.target == canvas) {
e.preventDefault();
}
drawing = false;
}, false);
//--------------------
// ADD CLICK function
//--------------------
function addUserGesture(x, y, dragging) {
clickX.push(x);
clickY.push(y);
clickD.push(dragging);
}
//-------------------
// RE DRAW function
//-------------------
function drawOnCanvas() {
var size = $("#slider").val();
ctx.clearRect(0, 0, size, size);
ctx.strokeStyle = canvasStrokeStyle;
ctx.lineJoin = canvasLineJoin;
ctx.lineWidth = canvasLineWidth;
for (var i = 0; i < clickX.length; i++) {
ctx.beginPath();
if(clickD[i] && i) {
ctx.moveTo(clickX[i-1], clickY[i-1]);
} else {
ctx.moveTo(clickX[i]-1, clickY[i]);
}
ctx.lineTo(clickX[i], clickY[i]);
ctx.closePath();
ctx.stroke();
}
}
//------------------------
// CLEAR CANVAS function
//------------------------
$("#clear-button").click(async function () {
var size = $("#slider").val();
ctx.clearRect(0, 0, size, size);
clickX = new Array();
clickY = new Array();
clickD = new Array();
$(".prediction-text").empty();
$(".percentage-text").empty();
$("#result_box").hide();
$("#helperText").show();
});
//-------------------------------------
// loader for cnn model
//-------------------------------------
async function loadModel() {
console.log("model loading..");
// clear the model variable
model = undefined;
// load the model using a HTTPS request (where you have stored your model files)
model = await tf.loadLayersModel("models/handwritingRecognitionModel.json");
console.log(model.summary);
$('#preloader').hide();
$("#helperText").show();
$('#predict-button').prop('disabled', false);
}
loadModel();
//-----------------------------------------------
// preprocess the canvas
//-----------------------------------------------
function preprocessCanvas(image) {
// resize the input image to target size of (1, 28, 28)
let tensor = tf.browser.fromPixels(image)
.resizeNearestNeighbor([28, 28])
.mean(2)
.expandDims(2)
.expandDims()
.toFloat();
console.log(tensor.shape);
return tensor.div(255.0);
}
//-----------------------------------------------
// check if canvas is blank
//-----------------------------------------------
function isCanvasBlank() {
// returns true if every pixel's uint32 representation is 0 (or "blank")
const pixelBuffer = new Uint32Array(
ctx.getImageData(0, 0, canvas.width, canvas.height).data.buffer
);
return !pixelBuffer.some(color => color !== 0);
}
//--------------------------------------------
// predict function
//--------------------------------------------
$("#predict-button").click(async function () {
// get image data from canvas
// var imageData = canvas.toDataURL('image/png');
// console.log(imageData);
if(!isCanvasBlank()){
// preprocess canvas
let tensor = preprocessCanvas(canvas);
// make predictions on the preprocessed image tensor
let predictions = await model.predict(tensor).data();
// get the model's prediction results
let results = Array.from(predictions);
// display the predictions in chart
$("#helperText").hide();
$("#result_box").removeClass('d-none');
$("#result_box").show();
//displayChart(results);
displayLabel(results);
console.log(results);
}
else{
alert("Please draw a digit in the canvas!");
}
});
//--------------------------------------------
// display prediction
//--------------------------------------------
function displayLabel(data) {
var max = data[0];
var maxIndex = 0;
for (var i = 1; i < data.length; i++) {
if (data[i] > max) {
maxIndex = i;
max = data[i];
}
}
$(".prediction-text").html(maxIndex)
$(".percentage-text").html(Math.trunc(max*100)+"%");
}
// canvas cannot be maximized to more value in phones
if($(window).width() < 450){
slider.max = 200;
}
// change canvas size based on slider value
$("#slider").on('input', function() {
canvas.setAttribute("width", this.value);
canvas.setAttribute("height", this.value);
});
/*
//------------------------------
// Chart to display predictions
//------------------------------
var chart = "";
var firstTime = 0;
function loadChart(label, data, modelSelected) {
var ctx = document.getElementById('chart_box').getContext('2d');
chart = new Chart(ctx, {
// The type of chart we want to create
type: 'bar',
// The data for our dataset
data: {
labels: label,
datasets: [{
label: modelSelected + " prediction",
backgroundColor: '#f50057',
borderColor: 'rgb(255, 99, 132)',
data: data,
}]
},
// Configuration options go here
options: {}
});
}
//----------------------------
// display chart with updated
// drawing from canvas
//----------------------------
function displayChart(data) {
var select_model = document.getElementById("select_model");
var select_option = "CNN";
label = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
if (firstTime == 0) {
loadChart(label, data, select_option);
firstTime = 1;
} else {
chart.destroy();
loadChart(label, data, select_option);
}
$('#chart_box').show();
}
*/