这个功能可以在保留边缘的情况下对图像平坦区域进行模糊滤波,这个功能可以实现很好的磨皮效果,它的算法如下:
/*
表面模糊滤波
*/
function surface(imgData, radius, threshold) {
var width = imgData.width,
height = imgData.height,
pixelData = tempData = imgData.data;
for (var i = 0; i < height; i++) {
for (var j = 0; j < width; j++) {
pos = (i * width + j) * 4;
sumr = sumrw = sumg = sumgw = sumb = sumbw = 0;
for (var n = -radius; n <= radius; n++) {
for (var m = -radius; m <= radius; m++) {
var x = CLIP3(i + n, 0, height - 1);
var y = CLIP3(j + m, 0, width - 1);
pos0 = (x * width + y) * 4;
k = 1.0 - Math.abs(tempData[pos0] - tempData[pos]) / (2.5 * threshold);
sumr += k * tempData[pos0];
sumrw += k;
k = 1.0 - Math.abs(tempData[pos0 + 1] - tempData[pos + 1]) / (2.5 * threshold);
sumg += k * tempData[pos0 + 1];
sumgw += k;
k = 1.0 - Math.abs(tempData[pos0 + 2] - tempData[pos + 2]) / (2.5 * threshold);
sumb += k * tempData[pos0 + 2];
sumbw += k;
}
}
pixelData[pos] = CLIP2((sumr / sumrw) >> 0, pixelData[pos]);
pixelData[pos + 1] = CLIP2((sumg / sumgw) >> 0, pixelData[pos + 1]);
pixelData[pos + 2] = CLIP2((sumb / sumbw) >> 0, pixelData[pos + 2]);
}
}
function CLIP2(a, b) {
if (a < 0 || a > 255) {
return b
} else {
return a
}
}
function CLIP3(a, b, c) {
return Math.min(Math.max(a, b), c)
}
imgData.data = pixelData;
return imgData;
}