二维中随机点上的值的插值

时间:2014-09-18 10:26:08

标签: algorithm interpolation

让我先举一个例子。在OpenGL中,当您在每个顶点上绘制具有不同颜色的三角形时,插入两者之间的点上的颜色值:

Triangle

现在,假设我收集了随机点,可以表示为(黑色被视为缺少颜色):

Points

如何有效地插入这些点,以便我得到均匀填充的图片?

3 个答案:

答案 0 :(得分:2)

我的建议是用一个值对颜色进行编码,然后从(xi,yi,ci)做一个表面拟合c = f(x,y),其中xi和yi是点的(x,y)坐标i和ci是点i处的编码颜色值。你不需要在边界空间做额外的处理,因为在边界点评估颜色值与在任何点评估颜色是一样的。

答案 1 :(得分:1)

  1. 将区域划分为三角形。从这里选择您的方法http://en.wikipedia.org/wiki/Point_set_triangulation

  2. 对于每个三角形,通常对单个三角形执行插值

答案 2 :(得分:1)

这个来自另一个 stackoverflow 问题的解决方案帮助了我: https://jsfiddle.net/87nw05kz/

const canvas = document.getElementById("testcanvas");
const context = canvas.getContext("2d");
const colors = [{x:10,y:10,r:255,g:0,b:0},
                            {x:190,y:10,r:0,g:127,b:0},
                            {x:100,y:190,r:0,g:0,b:255},
                            {x:200,y:100,r:0,g:0,b:0},
                            {x:190,y:190,r:127,g:255,b:127}];

function distance(x1, y1, x2, y2) {
        let dx = x1 - x2;
    let dy = y1 - y2;
    return Math.sqrt(dx * dx + dy * dy);
}
function calculateColor(x, y) {
        let total = 0;
        for (let i = 0; i < colors.length; i++) {
            let c = colors[i];
        let d = distance(c.x, c.y, x, y);
        if (d === 0) {
                return c;
        }
        d = 1 / (d * d);
        c.d = d;
        total += d;
        }
    let r = 0, g = 0, b = 0;
        for (let i = 0; i < colors.length; i++) {
            let c = colors[i];
            let ratio = c.d / total;
        r += ratio * c.r;
        g += ratio * c.g;
        b += ratio * c.b;
    }
    r = Math.floor(r);
    g = Math.floor(g);
    b = Math.floor(b);
    return {r:r,g:g,b:b};
}
              
function processImage() {
    const imgData = context.getImageData(0, 0, canvas.width, canvas.height);
    const pixels = imgData.data;
    const width = canvas.width;
    const height = canvas.height;
    const count = width * height * 4;
    for (let i = 0; i < count; i += 4) {
            let x = (i / 4) % width;
        let y = Math.floor(i / 4 / width);
        let color = calculateColor(x, y);
        pixels[i] = color.r;
        pixels[i+1] = color.g;
        pixels[i+2] = color.b;
        pixels[i+3] = 255;
        
    }
    context.putImageData(imgData, 0, 0);
}

processImage();