-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcanvasData.js
77 lines (58 loc) · 2.43 KB
/
canvasData.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
import * as tf from '@tensorflow/tfjs';
const IMAGE_SIZE = 784;
const NUM_DATASET_ELEMENTS = 65000;
export class myCanvas {
constructor() {
}
async load(ImgSrc) {
// Make a request for the MNIST sprited image.
const img = new Image();
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const imgRequest = new Promise((resolve, reject) => {
img.crossOrigin = '';
img.onload = () => {
img.width = img.naturalWidth;
img.height = img.naturalHeight;
const datasetBytesBuffer =
new ArrayBuffer(NUM_DATASET_ELEMENTS * IMAGE_SIZE * 4);
const chunkSize = 5000;
canvas.width = img.width;
canvas.height = chunkSize;
for (let i = 0; i < NUM_DATASET_ELEMENTS / chunkSize; i++) {
const datasetBytesView = new Float32Array(
datasetBytesBuffer, i * IMAGE_SIZE * chunkSize * 4,
IMAGE_SIZE * chunkSize);
ctx.drawImage(
img, 0, i * chunkSize, img.width, chunkSize, 0, 0, img.width,
chunkSize);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
for (let j = 0; j < imageData.data.length / 4; j++) {
// All channels hold an equal value since the image is grayscale, so
// just read the red channel.
datasetBytesView[j] = imageData.data[j * 4] / 255;
}
}
this.datasetImages = new Float32Array(datasetBytesBuffer);
resolve();
};
img.src = ImgSrc;
});
//const [imgResponse] =
await Promise.all([imgRequest]);
this.testImages = this.datasetImages;
}
nextTestBatch(batchSize) {
return this.nextBatch(batchSize, this.testImages);
}
nextBatch(batchSize, data) {
const batchImagesArray = new Float32Array(batchSize * IMAGE_SIZE);
for (let i = 0; i < batchSize; i++) {
const idx = 0;
const image = data.slice(idx * IMAGE_SIZE, 784);
batchImagesArray.set(image, i * IMAGE_SIZE);
}
const xs = tf.tensor2d(batchImagesArray, [batchSize, IMAGE_SIZE]);
return xs;
}
}