今天为大家带来的Demo不仅仅是图像滤镜处理,让我们来点和计算机视觉有关的,这也是我写GridJS的最初目的。
还不知道GridJS是什么的小伙伴们请看这里:http://v2ex.com/t/191612
原图:
检测角点结果(下面的图需要大家仔细看看,红点不是很明显,因为我偷懒只标了一个像素的尺寸):
代码:
var canvas = document.getElementById('workplace');
gridjs.open('cube.jpg', function(im) {
var H, corners, i;
im.grayscale();
H = harris(im.pixel.G);
corners = getHarrisPoint(H, 0.015, 10);
im.rgba();
for (i = 0; i < corners.length; i++) {
im.pixel.r[corners[i].y][corners[i].x] = 255;
im.pixel.g[corners[i].y][corners[i].x] = 0;
im.pixel.b[corners[i].y][corners[i].x] = 0;
}
im.update().show(canvas);
});
function harris(srcArray) {
var imx, imy, wxx, wyy, wxy, wdet, wtr, H,
g = gridjs;
imx = g.gauss(srcArray, 5, 1, 0);
imy = g.gauss(srcArray, 5, 1, 1);
wxx = g.gauss(g.square(imx), 5);
wyy = g.gauss(g.square(imy), 5);
wxy = g.gauss(g.mul(imx, imy), 5);
wdet = g.minus(g.mul(wxx, wyy), g.square(wxy));
wtr = g.add(wxx, wyy);
H = g.div(wdet, wtr, 0);
g.norm(H);
return H;
}
function getHarrisPoint(harrisArray, threshold, minDistance) {
var x, y, i, j, distance2,
minDistance2 = minDistance * minDistance,
index = 0,
width = harrisArray[0].length,
height = harrisArray.length,
points = [];
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
if (harrisArray[y][x] >= threshold) {
points[index++] = {
'x' : x,
'y' : y,
'h' : harrisArray[y][x]
}
}
}
}
points.sort(function(a, b) {
return b.h - a.h;
});
for (i = 0; i < points.length; i++) {
for (j = 0; j < i; j++) {
distance2 = (points[i].x - points[j].x) * (points[i].x - points[j].x) +
(points[i].y - points[j].y) * (points[i].y - points[j].y);
if (distance2 < minDistance2) {
points.splice(i, 1);
i--;
break;
}
}
}
return points;
}