var st = new Date().getTime();
var img = document.getElementsByTagName('img')[0];
// для начала представим изображение в виде массива оттенков серого
var data = rgb2l(img);
var hist = histogram(data);
var threshold = otsu(hist, data.length);
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
var context = canvas.getContext('2d');
var imageData = context.createImageData(img.width, img.height);
var j = 0;
var value;
for (var i = 0; i < imageData.data.length; i += 4) {
value = 255 * (data[j++] > threshold);
imageData.data[i] = value;
imageData.data[i + 1] = value;
imageData.data[i + 2] = value;
imageData.data[i + 3] = 255;
}
context.putImageData(imageData, 0, 0);
open(canvas.toDataURL());
var et = new Date().getTime();
console.log(et - st + ' ms');
function rgb2l(img) {
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
var context = canvas.getContext('2d');
context.drawImage(img, 0, 0, img.width, img.height);
var imageData = context.getImageData(0, 0, img.width, img.height);
var data = imageData.data;
var ret = new Uint8ClampedArray(img.width * img.height);
var r, g, b;
var j= 0;
for (var i = 0; i < data.length; i += 4) {
r = data[i];
g = data[i + 1];
b = data[i + 2];
ret[j] = Math.round(0.3 * r + 0.59 * g + 0.11 * b);
++j;
}
return ret;
}
function histogram(data) {
var ret = new Uint32Array(256);
for (var i = 0; i < data.length; ++i)
++ret[data[i]];
return ret;
}
// http://www.labbookpages.co.uk/software/ ... shold.html
function otsu(histogram, total) {
var sum = 0;
for (var i = 1; i < 256; ++i)
sum += i * histogram[i];
var sumB = 0;
var wB = 0;
var wF = 0;
var mB;
var mF;
var max = 0;
var between;
var threshold = 0;
for (var i = 0; i < 256; ++i) {
wB += histogram[i];
if (wB == 0)
continue;
wF = total - wB;
if (wF == 0)
break;
sumB += i * histogram[i];
mB = sumB / wB;
mF = (sum - sumB) / wF;
between = wB * wF * Math.pow(mB - mF, 2);
if (between > max) {
max = between;
threshold = i;
}
}
return threshold;
}