插值图像像素

时间:2017-02-05 15:31:30

标签: java image interpolation

我想为我的3D引擎采样高度图。可能会发生我的地形上的顶点多于图像中的像素。我创建了以下方法:

public float interpolateFromImage(BufferedImage image, float x, float y){

这将获取图像以及x和y坐标。坐标以百分比给出。 我的方法是计算附近像素和给定坐标之间的距离。这工作正常但我最终得到了这个: Output Image; size 1000x1000.  Input is a 4x4 picture

可以清楚地看到边缘不像它们应该的那样光滑。

我使用了以下代码:

    int topLeftX = (int) (x * (image.getWidth()-1));      //index of topLeft pixel
    int topLeftY = (int) (y * (image.getHeight()-1));     //index of topLeft pixel

    float[] distances = new float[4];  
    float total = 0;
    for(int j = topLeftX ; j < topLeftX + 2; j++){           //run through all 4 nearby pixels
        for(int k = topLeftY ; k < topLeftY + 2; k++){
            float dist = (float) Math.sqrt(                    //pythagoras for the distance
                    (x- j/ (float)(image.getWidth()-1)) *
                            (x- j/ (float)(image.getWidth()-1)) +
                            (y- k/ (float)(image.getHeight()-1)) *
                                    (y- k/ (float)(image.getHeight()-1)));
            if(dist < 0.001){
                return new Color(image.getRGB(j,k)).getRed();
            }
            distances[(j-topLeftX) * 2 + (k-topLeftY)] = (1f / image.getWidth()) / (dist * dist);
            total += distances[(j-topLeftX) * 2 + (k-topLeftY)];
        }
    }
    float h = 0;
    for(int j = topLeftX ; j < topLeftX + 2; j++){
        for(int k = topLeftY ; k < topLeftY + 2; k++){
            float p = distances[(j-topLeftX) * 2 + (k-topLeftY)] / total;
            h+= new Color(image.getRGB(j,k)).getRed() * p;
        }
    }
    return h;

有谁知道我需要如何更改我的代码? 我很高兴得到任何建议和帮助:)。

1 个答案:

答案 0 :(得分:0)

您正在根据所有四个角的反平方距离来权衡颜色。这里的问题是:边缘上的像素颜色受到角落颜色的影响。边缘两侧的像素颜色不同,因为它们是从不同的四个角集合计算的。

解决方案是使用一些常见的插值,如双线性或双三次插值。