双三次算法与双线性插值相比,需要计算相邻16个点的输入像素,即w方向坐标分别为w - 1、w、w + 1、 w + 2;h方向坐标分别为h - 1、h、 h + 1、h + 2。如何计算每个点对应的权重呢?opencv的计算方法是这样的:
fx = (float)((dx+0.5)*scale_x - 0.5);
sx = cvFloor(fx);
fx -= sx;
BiBubic(ii - fx); //ii值为-1/0/1/2
#define ALPHA -0.75
/*
(a + 2)|x|^3 - (a + 3)|x|^2 + 1 for |x| <= 1
w(x) = { a|x|^3 - 5a|x|^2 + 8a|x| - 4a for 1 < |x| < 2
0 otherwise
*/
inline float BiBubic(float x)
{
float dst_val = 0;
float val = ABS(x);
if (val <= 1)
{
dst_val = (ALPHA + 2) * val * val * val - (ALPHA + 3) * val * val + 1;
}
else if (val > 1 && val < 2)
{
dst_val = ALPHA * val * val * val - 5 * ALPHA * val * val + 8 * ALPHA * val - 4 * ALPHA;
}
return dst_val;
}
然后进行累加求和就可以了。
大致流程如下(细节与opencv不一样,具体需要参考opencv的具体代码)
float scale_h = (float)lSrcHeight / lDstHeight;
float scale_w = (float)lSrcWidth / lDstWidth;
for (dy = 0; dy < lDstHeight; dy++)
{
for (dx = 0; dx < lDstWidth; dx++)
{
float src_h = dy * scale_h;
float src_w = dx * scale_w;
int w_idx = floor(src_w);
int h_idx = floor(src_h);
float w_weight = src_w - w_idx;
float h_weight = src_h - h_idx;
float tmp_val = 0;
for (ii = -1; ii <= 2; ii++)
{
for (jj = -1; jj <= 2; jj++)
{
if (w_idx + jj < 0 || h_idx + ii < 0 || w_idx + jj >= lSrcWidth || h_idx + ii >= lSrcHeight)
{
continue; //也可考虑复制边缘的数据进行计算
}
tmp_val += pSrcY[(h_idx + ii) * lSrcStrideY + w_idx + jj] * BiBubic(ii - h_weight) * BiBubic(jj - w_weight);
}
}
tmp_val = MAX(0, tmp_val);
tmp_val = MIN(255, tmp_val);
pDstY[dy * lDstStrideY + dx] = (MUInt8)tmp_val;
}
}
if(h_idx < 0) h_idx = 0;if(h_idx>lSrcHeight-1)h_idx=lSrcHeight - 1;即将边缘的数据复制一份参与计算,但是bibubic(ii - h_weight)中的ii必须还是-1,0, 1,2;对于w的处理和h的处理一样;