forked from usnistgov/OpenSeadragonFiltering
-
Notifications
You must be signed in to change notification settings - Fork 0
/
openseadragon-filtering.js
493 lines (465 loc) · 20 KB
/
openseadragon-filtering.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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
/*
* This software was developed at the National Institute of Standards and
* Technology by employees of the Federal Government in the course of
* their official duties. Pursuant to title 17 Section 105 of the United
* States Code this software is not subject to copyright protection and is
* in the public domain. This software is an experimental system. NIST assumes
* no responsibility whatsoever for its use by other parties, and makes no
* guarantees, expressed or implied, about its quality, reliability, or
* any other characteristic. We would appreciate acknowledgement if the
* software is used.
*/
/**
*
* @author Antoine Vandecreme <[email protected]>
*/
(function() {
'use strict';
var $ = window.OpenSeadragon;
if (!$) {
$ = require('openseadragon');
if (!$) {
throw new Error('OpenSeadragon is missing.');
}
}
// Requires OpenSeadragon >=2.1
if (!$.version || $.version.major < 2 ||
$.version.major === 2 && $.version.minor < 1) {
throw new Error(
'Filtering plugin requires OpenSeadragon version >= 2.1');
}
$.Viewer.prototype.setFilterOptions = function(options) {
if (!this.filterPluginInstance) {
options = options || {};
options.viewer = this;
this.filterPluginInstance = new $.FilterPlugin(options);
} else {
setOptions(this.filterPluginInstance, options);
}
};
/**
* @class FilterPlugin
* @param {Object} options The options
* @param {OpenSeadragon.Viewer} options.viewer The viewer to attach this
* plugin to.
* @param {String} [options.loadMode='async'] Set to sync to have the filters
* applied synchronously. It will only work if the filters are all synchronous.
* Note that depending on how complex the filters are, it may also hang the browser.
* @param {Object[]} options.filters The filters to apply to the images.
* @param {OpenSeadragon.TiledImage[]} options.filters[x].items The tiled images
* on which to apply the filter.
* @param {function|function[]} options.filters[x].processors The processing
* function(s) to apply to the images. The parameters of this function are
* the context to modify and a callback to call upon completion.
*/
$.FilterPlugin = function(options) {
options = options || {};
if (!options.viewer) {
throw new Error('A viewer must be specified.');
}
var self = this;
this.viewer = options.viewer;
this.viewer.addHandler('tile-loaded', tileLoadedHandler);
this.viewer.addHandler('tile-drawing', tileDrawingHandler);
// filterIncrement allows to determine whether a tile contains the
// latest filters results.
this.filterIncrement = 0;
setOptions(this, options);
function tileLoadedHandler(event) {
var processors = getFiltersProcessors(self, event.tiledImage);
if (processors.length === 0) {
return;
}
var tile = event.tile;
var image = event.image;
if (image !== null && image !== undefined) {
var canvas = window.document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext('2d');
context.drawImage(image, 0, 0);
tile._renderedContext = context;
var callback = event.getCompletionCallback();
applyFilters(context, processors, callback);
tile._filterIncrement = self.filterIncrement;
}
}
function applyFilters(context, filtersProcessors, callback) {
if (callback) {
var currentIncrement = self.filterIncrement;
var callbacks = [];
for (var i = 0; i < filtersProcessors.length - 1; i++) {
(function(i) {
callbacks[i] = function() {
// If the increment has changed, stop the computation
// chain immediately.
if (self.filterIncrement !== currentIncrement) {
return;
}
filtersProcessors[i + 1](context, callbacks[i + 1]);
};
})(i);
}
callbacks[filtersProcessors.length - 1] = function() {
// If the increment has changed, do not call the callback.
// (We don't want OSD to draw an outdated tile in the canvas).
if (self.filterIncrement !== currentIncrement) {
return;
}
callback();
};
filtersProcessors[0](context, callbacks[0]);
} else {
for (var i = 0; i < filtersProcessors.length; i++) {
filtersProcessors[i](context, function() {
});
}
}
}
function tileDrawingHandler(event) {
var tile = event.tile;
var rendered = event.rendered;
if (rendered._filterIncrement === self.filterIncrement) {
return;
}
var processors = getFiltersProcessors(self, event.tiledImage);
if (processors.length === 0) {
if (rendered._originalImageData) {
// Restore initial data.
rendered.putImageData(rendered._originalImageData, 0, 0);
delete rendered._originalImageData;
}
rendered._filterIncrement = self.filterIncrement;
return;
}
if (rendered._originalImageData) {
// The tile has been previously filtered (by another filter),
// restore it first.
rendered.putImageData(rendered._originalImageData, 0, 0);
} else {
rendered._originalImageData = rendered.getImageData(
0, 0, rendered.canvas.width, rendered.canvas.height);
}
if (tile._renderedContext) {
if (tile._filterIncrement === self.filterIncrement) {
var imgData = tile._renderedContext.getImageData(0, 0,
tile._renderedContext.canvas.width,
tile._renderedContext.canvas.height);
rendered.putImageData(imgData, 0, 0);
delete tile._renderedContext;
delete tile._filterIncrement;
rendered._filterIncrement = self.filterIncrement;
return;
}
delete tile._renderedContext;
delete tile._filterIncrement;
}
applyFilters(rendered, processors);
rendered._filterIncrement = self.filterIncrement;
}
};
function setOptions(instance, options) {
options = options || {};
var filters = options.filters;
instance.filters = !filters ? [] :
$.isArray(filters) ? filters : [filters];
for (var i = 0; i < instance.filters.length; i++) {
var filter = instance.filters[i];
if (!filter.processors) {
throw new Error('Filter processors must be specified.');
}
filter.processors = $.isArray(filter.processors) ?
filter.processors : [filter.processors];
}
instance.filterIncrement++;
if (options.loadMode === 'sync') {
instance.viewer.forceRedraw();
} else {
var itemsToReset = [];
for (var i = 0; i < instance.filters.length; i++) {
var filter = instance.filters[i];
if (!filter.items) {
itemsToReset = getAllItems(instance.viewer.world);
break;
}
if ($.isArray(filter.items)) {
for (var j = 0; j < filter.items.length; j++) {
addItemToReset(filter.items[j], itemsToReset);
}
} else {
addItemToReset(filter.items, itemsToReset);
}
}
for (var i = 0; i < itemsToReset.length; i++) {
itemsToReset[i].reset();
}
}
}
function addItemToReset(item, itemsToReset) {
if (itemsToReset.indexOf(item) >= 0) {
throw new Error('An item can not have filters ' +
'assigned multiple times.');
}
itemsToReset.push(item);
}
function getAllItems(world) {
var result = [];
for (var i = 0; i < world.getItemCount(); i++) {
result.push(world.getItemAt(i));
}
return result;
}
function getFiltersProcessors(instance, item) {
if (instance.filters.length === 0) {
return [];
}
var globalProcessors = null;
for (var i = 0; i < instance.filters.length; i++) {
var filter = instance.filters[i];
if (!filter.items) {
globalProcessors = filter.processors;
} else if (filter.items === item ||
$.isArray(filter.items) && filter.items.indexOf(item) >= 0) {
return filter.processors;
}
}
return globalProcessors ? globalProcessors : [];
}
$.Filters = {
THRESHOLDING: function(threshold) {
if (threshold < 0 || threshold > 255) {
throw new Error('Threshold must be between 0 and 255.');
}
return function(context, callback) {
var imgData = context.getImageData(
0, 0, context.canvas.width, context.canvas.height);
var pixels = imgData.data;
for (var i = 0; i < pixels.length; i += 4) {
var r = pixels[i];
var g = pixels[i + 1];
var b = pixels[i + 2];
var v = (r + g + b) / 3;
pixels[i] = pixels[i + 1] = pixels[i + 2] =
v < threshold ? 0 : 255;
}
context.putImageData(imgData, 0, 0);
callback();
};
},
BRIGHTNESS: function(adjustment) {
if (adjustment < -255 || adjustment > 255) {
throw new Error(
'Brightness adjustment must be between -255 and 255.');
}
var precomputedBrightness = [];
for (var i = 0; i < 256; i++) {
precomputedBrightness[i] = i + adjustment;
}
return function(context, callback) {
var imgData = context.getImageData(
0, 0, context.canvas.width, context.canvas.height);
var pixels = imgData.data;
for (var i = 0; i < pixels.length; i += 4) {
pixels[i] = precomputedBrightness[pixels[i]];
pixels[i + 1] = precomputedBrightness[pixels[i + 1]];
pixels[i + 2] = precomputedBrightness[pixels[i + 2]];
}
context.putImageData(imgData, 0, 0);
callback();
};
},
CONTRAST: function(adjustment) {
if (adjustment < 0) {
throw new Error('Contrast adjustment must be positive.');
}
var precomputedContrast = [];
for (var i = 0; i < 256; i++) {
precomputedContrast[i] = i * adjustment;
}
return function(context, callback) {
var imgData = context.getImageData(
0, 0, context.canvas.width, context.canvas.height);
var pixels = imgData.data;
for (var i = 0; i < pixels.length; i += 4) {
pixels[i] = precomputedContrast[pixels[i]];
pixels[i + 1] = precomputedContrast[pixels[i + 1]];
pixels[i + 2] = precomputedContrast[pixels[i + 2]];
}
context.putImageData(imgData, 0, 0);
callback();
};
},
GAMMA: function(adjustment) {
if (adjustment < 0) {
throw new Error('Gamma adjustment must be positive.');
}
var precomputedGamma = [];
for (var i = 0; i < 256; i++) {
precomputedGamma[i] = Math.pow(i / 255, adjustment) * 255;
}
return function(context, callback) {
var imgData = context.getImageData(
0, 0, context.canvas.width, context.canvas.height);
var pixels = imgData.data;
for (var i = 0; i < pixels.length; i += 4) {
pixels[i] = precomputedGamma[pixels[i]];
pixels[i + 1] = precomputedGamma[pixels[i + 1]];
pixels[i + 2] = precomputedGamma[pixels[i + 2]];
}
context.putImageData(imgData, 0, 0);
callback();
};
},
GREYSCALE: function() {
return function(context, callback) {
var imgData = context.getImageData(
0, 0, context.canvas.width, context.canvas.height);
var pixels = imgData.data;
for (var i = 0; i < pixels.length; i += 4) {
var val = (pixels[i] + pixels[i + 1] + pixels[i + 2]) / 3;
pixels[i] = val;
pixels[i + 1] = val;
pixels[i + 2] = val;
}
context.putImageData(imgData, 0, 0);
callback();
};
},
INVERT: function() {
var precomputedInvert = [];
for (var i = 0; i < 256; i++) {
precomputedInvert[i] = 255 - i;
}
return function(context, callback) {
var imgData = context.getImageData(
0, 0, context.canvas.width, context.canvas.height);
var pixels = imgData.data;
for (var i = 0; i < pixels.length; i += 4) {
pixels[i] = precomputedInvert[pixels[i]];
pixels[i + 1] = precomputedInvert[pixels[i + 1]];
pixels[i + 2] = precomputedInvert[pixels[i + 2]];
}
context.putImageData(imgData, 0, 0);
callback();
};
},
MORPHOLOGICAL_OPERATION: function(kernelSize, comparator) {
if (kernelSize % 2 === 0) {
throw new Error('The kernel size must be an odd number.');
}
var kernelHalfSize = Math.floor(kernelSize / 2);
if (!comparator) {
throw new Error('A comparator must be defined.');
}
return function(context, callback) {
var width = context.canvas.width;
var height = context.canvas.height;
var imgData = context.getImageData(0, 0, width, height);
var originalPixels = context.getImageData(0, 0, width, height)
.data;
var offset;
for (var y = 0; y < height; y++) {
for (var x = 0; x < width; x++) {
offset = (y * width + x) * 4;
var r = originalPixels[offset];
var g = originalPixels[offset + 1];
var b = originalPixels[offset + 2];
for (var j = 0; j < kernelSize; j++) {
for (var i = 0; i < kernelSize; i++) {
var pixelX = x + i - kernelHalfSize;
var pixelY = y + j - kernelHalfSize;
if (pixelX >= 0 && pixelX < width &&
pixelY >= 0 && pixelY < height) {
offset = (pixelY * width + pixelX) * 4;
r = comparator(originalPixels[offset], r);
g = comparator(
originalPixels[offset + 1], g);
b = comparator(
originalPixels[offset + 2], b);
}
}
}
imgData.data[offset] = r;
imgData.data[offset + 1] = g;
imgData.data[offset + 2] = b;
}
}
context.putImageData(imgData, 0, 0);
callback();
};
},
CONVOLUTION: function(kernel) {
if (!$.isArray(kernel)) {
throw new Error('The kernel must be an array.');
}
var kernelSize = Math.sqrt(kernel.length);
if ((kernelSize + 1) % 2 !== 0) {
throw new Error('The kernel must be a square matrix with odd' +
'width and height.');
}
var kernelHalfSize = (kernelSize - 1) / 2;
return function(context, callback) {
var width = context.canvas.width;
var height = context.canvas.height;
var imgData = context.getImageData(0, 0, width, height);
var originalPixels = context.getImageData(0, 0, width, height)
.data;
var offset;
for (var y = 0; y < height; y++) {
for (var x = 0; x < width; x++) {
var r = 0;
var g = 0;
var b = 0;
for (var j = 0; j < kernelSize; j++) {
for (var i = 0; i < kernelSize; i++) {
var pixelX = x + i - kernelHalfSize;
var pixelY = y + j - kernelHalfSize;
if (pixelX >= 0 && pixelX < width &&
pixelY >= 0 && pixelY < height) {
offset = (pixelY * width + pixelX) * 4;
var weight = kernel[j * kernelSize + i];
r += originalPixels[offset] * weight;
g += originalPixels[offset + 1] * weight;
b += originalPixels[offset + 2] * weight;
}
}
}
offset = (y * width + x) * 4;
imgData.data[offset] = r;
imgData.data[offset + 1] = g;
imgData.data[offset + 2] = b;
}
}
context.putImageData(imgData, 0, 0);
callback();
};
},
COLORMAP: function(cmap, ctr) {
var resampledCmap = cmap.slice(0);
var diff = 255 - ctr;
for(var i = 0; i < 256; i++) {
var position = 0;
if(i > ctr) {
position = Math.min((i - ctr) / diff * 128 + 128,255) | 0;
}else{
position = Math.max(0, i / (ctr / 128)) | 0;
}
resampledCmap[i] = cmap[position];
}
return function(context, callback) {
var imgData = context.getImageData(
0, 0, context.canvas.width, context.canvas.height);
var pxl = imgData.data;
for (var i = 0; i < pxl.length; i += 4) {
var v = (pxl[i] + pxl[i + 1] + pxl[i + 2]) / 3 | 0;
var c = resampledCmap[v];
pxl[i] = c[0];
pxl[i + 1] = c[1];
pxl[i + 2] = c[2];
}
context.putImageData(imgData, 0, 0);
callback();
};
}
};
}());