-
Notifications
You must be signed in to change notification settings - Fork 19
/
image-util.js
75 lines (65 loc) · 2.03 KB
/
image-util.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
class ImageUtil {
/**
* Flattens a RGBA channel data into grey scale float array
*/
static flatten(data, options) {
const w = options.width || 0;
const h = options.height || 0;
const flat = [];
for (let i = 0; i < w * h; ++i) {
const j = i * 4;
const newVal = (data[j+0] + data[j+1] + data[j+2] + data[j+3]) / 4.0 ;
flat.push( newVal / 255.0 );
}
return flat;
}
/**
* Unflatten single channel to RGBA
*/
static unflatten(data, options) {
const w = options.width || 0;
const h = options.height || 0;
const unflat = [];
for (let i = 0; i < w * h; ++i) {
const val = data[i];
unflat.push(data[i] * 255);
unflat.push(data[i] * 255);
unflat.push(data[i] * 255);
unflat.push(255);
}
return unflat;
}
/**
* Load image data into RGBA numeric array, which is
* somewhat compatible with tensor data structure
*
* @param {string} url - the image URL
* @param {object} options
* @param {number} options.width - optional, resize to specified width
* @param {number} options.height - optional, resize to specified height
*
* FIXME: reuse canvas element if available
* FIXME: add option for channel filters
*/
static async loadImage(url, options = {}) {
const img = new Image();
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
window.ctx = ctx;
const imgRequest = new Promise((resolve, reject) => {
img.crossOrigin = '';
img.onload = () => {
img.width = options.width || img.naturalWidth;
img.height = options.height || img.naturalHeight;
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0 , 0, img.width, img.height);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
// ctx.drawImage(img, 0, i * chunkSize, img.width, chunkSize, 0, 0, img.width, chunkSize);
resolve(imageData);
};
img.src = url;
});
return imgRequest;
}
}