-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtfjs_main.html
More file actions
executable file
·207 lines (185 loc) · 7.33 KB
/
tfjs_main.html
File metadata and controls
executable file
·207 lines (185 loc) · 7.33 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
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
<!doctype html>
<html lang="en">
<head>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-H0NW5Z2MYC"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-H0NW5Z2MYC');
</script>
<title>Digit Recognition WebApp</title>
<meta name="description" content="Simple Machine Learning Model into a WebApp using TensorFlow.js">
<meta name="keywords" content="Machine Learning, TensorFlow.js">
<meta name="author" content="Mattia Bergagio">
<style>
body {
touch-action: none; /*https://developer.mozilla.org/en-US/docs/Web/CSS/touch-action*/
font-family: "Roboto";
}
h1 {
margin: 50px;
font-size: 70px;
text-align: center;
}
#paint {
border:3px solid red;
margin: auto;
}
#predicted {
font-size: 60px;
margin-top: 60px;
text-align: center;
}
#number {
border: 3px solid black;
margin: auto;
margin-top: 30px;
text-align: center;
vertical-align: middle;
}
#clear {
margin: auto;
margin-top: 70px;
padding: 30px;
text-align: center;
}
</style>
</head>
<body>
<!--<script type="text/javascript" src="http://livejs.com/live.js"></script>-->
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<!-- load TensorFlow.js -->
<!-- https://www.tensorflow.org/js/tutorials/setup#usage_via_script_tag -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.5.2/dist/tf.min.js"></script>
<!-- title -->
<h1>Digit Recognition WebApp - copy of Aguayo's work</h1>
<div id="paint">
<canvas id="myCanvas"></canvas>
</div>
<div id="predicted">
Recognized digit
<div id="number"></div>
<button id="clear">Clear</button>
</div>
<!-- Place your code in the script tag below. You can also use an external .js file -->
<script>
// There is no 'import' statement: 'tf' is available on the index-page
// because of the script tag above
var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
if (isMobile) {
$('#paint').css({'width': '60%'});
$('#number').css({'width': '30%', 'font-size': '240px'});
$('#clear').css({'font-size': '50px'});
} else {
$('#paint').css({'width': '300px'});
$('#number').css({'width': '150px', 'font-size': '120px'});
$('#clear').css({'font-size': '35px'});
}
var cw = $('#paint').width();
$('#paint').css({'height': cw + 'px'});
cw = $('#number').width();
$('#number').css({'height': cw + 'px'});
// From https://www.html5canvastutorials.com/labs/html5-canvas-paint-application/
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var compuetedStyle = getComputedStyle(document.getElementById('paint'));
canvas.width = parseInt(compuetedStyle.getPropertyValue('width'));
canvas.height = parseInt(compuetedStyle.getPropertyValue('height'));
var mouse = {x: 0, y: 0};
canvas.addEventListener('mousemove', function(e) {
mouse.x = e.pageX - this.offsetLeft;
mouse.y = e.pageY - this.offsetTop;
}, false);
context.lineWidth = isMobile ? 60 : 25;
context.lineJoin = 'round';
context.lineCap = 'round';
context.strokeStyle = '#0000FF';
// hook mouse events to draw into the Canvas
canvas.addEventListener('mousedown', function(e) {
context.moveTo(mouse.x, mouse.y);
context.beginPath();
canvas.addEventListener('mousemove', onPaint, false);
}, false);
// Once we can draw, fetch the image upon mouse up
canvas.addEventListener('mouseup', function() {
$('#number').html('<img id="spinner" src="https://media.giphy.com/media/3oEjI6SIIHBdRxXI40/giphy.gif"/>');
canvas.removeEventListener('mousemove', onPaint, false);
var img = new Image();
img.onload = function() {
// scale the fetched image down to 28 by 28 pixels so that it matches the trained model
context.drawImage(img, 0, 0, 28, 28);
// data is a 1D array with RGBA values
// Our model only takes 0 to 1 values (or 0 from 255 in grayscale)
// Since we are drawing Blue into the canvas, slice the array in chunks of 4 and take every 3rd element,
// so use data[i + 2]
data = context.getImageData(0, 0, 28, 28).data;
// keep data into an input array and pass it to a
// predict function defined later
var input = [];
for(var i = 0; i < data.length; i += 4) {
input.push(data[i + 2] / 255);
}
predict(input);
};
img.src = canvas.toDataURL('image/png');
}, false);
// draw into Canvas
var onPaint = function() {
context.lineTo(mouse.x, mouse.y);
context.stroke();
};
// load the trained model
// https://www.tensorflow.org/js/tutorials/conversion/import_keras#step_2_load_the_model_into_tensorflowjs
// load*Model(...) fetches model.json, and then makes additional HTTP(S) requests
// to obtain the sharded weight files referenced in the model.json weight manifest.
// This approach allows all of these files to be cached by the browser
// (and perhaps by additional caching servers on the internet),
// because the model.json and the weight shards are each smaller than the typical cache file size limit.
// Thus a model is likely to load more quickly on subsequent occasions
tf.loadLayersModel('model/model.json').then(function(model) {
window.model = model;
});
// http://bencentra.com/code/2014/12/05/html5-canvas-touch-events.html
// Set up touch events for mobile etc
// Add the touch action to disable scrolling
canvas.addEventListener('touchstart', function (e) {
var touch = e.touches[0];
canvas.dispatchEvent(new MouseEvent('mousedown', {
clientX: touch.clientX,
clientY: touch.clientY
}));
}, false);
canvas.addEventListener('touchend', function (e) {
canvas.dispatchEvent(new MouseEvent('mouseup', {}));
}, false);
canvas.addEventListener('touchmove', function (e) {
var touch = e.touches[0];
canvas.dispatchEvent(new MouseEvent('mousemove', {
clientX: touch.clientX,
clientY: touch.clientY
}));
}, false);
// predict function
var predict = function(input) {
if (window.model) {
// once we have the data, feed it into the model upon mouseup
window.model.predict([tf.tensor(input).reshape([1, 28, 28, 1])]).array().then(function(scores){
scores = scores[0];
predicted = scores.indexOf(Math.max(...scores));
$('#number').html(predicted);
});
} else {
// The model takes a bit to load. If we are too fast, wait
setTimeout(function(){predict(input)}, 50);
}
}
// clear drawing
$('#clear').click(function(){
context.clearRect(0, 0, canvas.width, canvas.height);
$('#number').html('');
});
</script>
</body>
</html>