双线性插值,我的实现有问题

4

我在尝试实现一个双线性插值函数,但是出现了错误的输出结果。我似乎无法找出问题所在,希望能得到帮助以找到正确的方向。

double lerp(double c1, double c2, double v1, double v2, double x)
{
if( (v1==v2) ) return c1;
double inc = ((c2-c1)/(v2 - v1)) * (x - v1);
double val = c1 + inc;
return val;
};

void bilinearInterpolate(int width, int height)
{
// if the current size is the same, do nothing
if(width == GetWidth() && height == GetHeight())
    return;

//Create a new image
std::unique_ptr<Image2D> image(new Image2D(width, height));

// x and y ratios
double rx = (double)(GetWidth()) / (double)(image->GetWidth()); // oldWidth / newWidth
double ry = (double)(GetHeight()) / (double)(image->GetHeight());   // oldWidth / newWidth


// loop through destination image
for(int y=0; y<height; ++y)
{
    for(int x=0; x<width; ++x)
    {
        double sx = x * rx;
        double sy = y * ry;

        uint xl = std::floor(sx);
        uint xr = std::floor(sx + 1);
        uint yt = std::floor(sy);
        uint yb = std::floor(sy + 1);

        for (uint d = 0; d < image->GetDepth(); ++d)
        {
            uchar tl    = GetData(xl, yt, d);
            uchar tr    = GetData(xr, yt, d);
            uchar bl    = GetData(xl, yb, d);
            uchar br    = GetData(xr, yb, d);
            double t    = lerp(tl, tr, xl, xr, sx);
            double b    = lerp(bl, br, xl, xr, sx);
            double m    = lerp(t, b, yt, yb, sy);
            uchar val   = std::floor(m + 0.5);
            image->SetData(x,y,d,val);
        }
    }
}

//Cleanup
mWidth = width; mHeight = height;
std::swap(image->mData, mData);
}

输入图像(宽高均为4个像素)

输入图像(宽高均为4个像素)

我的输出

我的输出

期望输出(Photoshop的双线性插值)

期望输出(Photoshop的双线性插值)


1
Photoshop是否一定会在RGB颜色空间内执行插值?如果它在HSL等颜色空间内执行,那么结果将会不同。 - Oliver Charlesworth
你的输出似乎与 Photoshop 相比,向左上方移动了 0.5 像素。 - hamstergene
1个回答

9
Photoshop的算法假设每个源像素的颜色位于像素的中心,而您的算法假设颜色位于其左上角。这会导致您的结果向上和向左移动半个像素,与Photoshop相比。
另一种看待这个问题的方式是,您的算法将x坐标范围(0,srcWidth)映射到(0,dstWidth),而Photoshop将(-0.5,srcWidth-0.5)映射到(-0.5,dstWidth-0.5),y坐标也是如此。
改为:
double sx = x * rx;
double sy = y * ry;

您可以使用:

double sx = (x + 0.5) * rx - 0.5;
double sy = (y + 0.5) * ry - 0.5;

为了获得类似的结果。请注意,这可能会给您sxsy带来负值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接