/
numbers.js
91 lines (72 loc) · 2.13 KB
/
numbers.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
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext("2d")
let drawing = false
let model
let prediction = document.getElementById("prediction")
// window.addEventListener("load", () => {
// canvas.height = window.innerHeight / 2
// canvas.width = window.innerWidth / 4
// })
// window.addEventListener("resize", () => {
// canvas.height = window.innerHeight / 2
// canvas.width = window.innerWidth / 4
// }
// )
function startPosition(e) {
drawing = true
draw(e)
}
function finishedPosition() {
drawing = false
ctx.beginPath()
}
function draw(e) {
if (!drawing) return
const position = getMousePos(canvas, e)
ctx.lineWidth = 20
ctx.lineCap = "round"
ctx.strokeStyle = "white";
ctx.lineTo(position.x, position.y)
ctx.stroke()
ctx.beginPath()
ctx.moveTo(position.x, position.y)
}
function getMousePos(canvas, evt) {
const rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
async function loadModel() {
model = undefined
model = await tf.loadLayersModel("models/model.json")
}
loadModel()
function preprocessImage(image){
let tensor = tf.browser.fromPixels(image)
.resizeNearestNeighbor([28,28])
.mean(2)
.expandDims(2)
.expandDims()
.toFloat()
return tensor.div(255.0)
}
canvas.addEventListener("mousedown", startPosition)
canvas.addEventListener("mouseup", finishedPosition)
canvas.addEventListener("mousemove", draw)
const clearBtn = document.getElementById('clearBtn')
const predictBtn = document.getElementById('predictBtn')
const openCVBtn = document.getElementById('openCVBtn')
clearBtn.addEventListener('click', () => {
prediction.innerHTML = ""
ctx.clearRect(0, 0, canvas.width, canvas.height)
})
predictBtn.addEventListener('click', async () => {
let tensor = preprocessImage(canvas)
let predictions = await model.predict(tensor).data();
let results = Array.from(predictions)
index = results.indexOf(Math.max(...results))
console.log(`Prediction is ${index}`)
prediction.innerHTML = index
})