我使用双线性插值实现了一个 CUDA 函数来调整图像大小。该函数应该给出正确的结果(视觉上),直到我在一个小矩阵上进行测试以检查输出图像的确切值。我得到的结果与 OpenCV 和 MATLAB 的结果不同。我在我的算法中找不到任何明显的缺陷。有人可以帮我吗?
双线性插值器功能:
texture<float, cudaTextureType2D> tex32f;
//Device function
__device__ float blinterp(const float xIndex, const float yIndex)
{
//floor the coordinates to get to the nearest valid pixel
const int intX = static_cast<int>(xIndex);
const int intY = static_cast<int>(yIndex);
//Set weights of pixels according to distance from actual location
const float a = xIndex - intX;
const float b = yIndex - intY;
/* _____________________
*| | |
*|(1-a)(1-b)| (a)(1-b) |
*|__________|__________|
*| | |
*| (1-a)(b) | (a)(b) |
*|__________|__________|
*/
//Compute the weighted average of 4 nearest pixels
float out = (1 - a) * (1 - b) * tex2D(tex32f, intX,intY)
+ (a) * (1 - b) * tex2D(tex32f,intX + 1,intY)
+ (1 - a) * (b) * tex2D(tex32f, intX,intY + 1)
+ (a * b) * tex2D(tex32f,intX + 1,intY + 1);
return out;
}
调整内核大小:
__global__ void kernel_resize(float* dst, int dstWidth, int dstHeight, int dstPitch, float xScale, float yScale)
{
const int xIndex = blockIdx.x * blockDim.x + threadIdx.x;
const int yIndex = blockIdx.y * blockDim.y + threadIdx.y;
if(xIndex>=dstWidth || yIndex>=dstHeight) return;
const unsigned int tid = yIndex * dstPitch + xIndex;
const float inXindex = xIndex * xScale;
const float inYindex = yIndex * yScale;
dst[tid] = blinterp(inXindex,inYindex);
}
包装功能:
int resize_32f_c1(float* src,float* dst,int srcWidth,int srcHeight, int srcPitch, int dstWidth,int dstHeight,int dstPitch)
{
if((srcWidth == dstWidth) && (srcHeight == dstHeight))
{
cudaMemcpy2D(dst,dstPitch,src,srcPitch,srcWidth * sizeof(float),srcHeight,cudaMemcpyDeviceToDevice);
return 0;
}
cudaBindTexture2D(NULL,tex32f,src,srcWidth,srcHeight,srcPitch);
dim3 Block(16,16);
dim3 Grid((dstWidth + Block.x - 1)/Block.x, (dstHeight + Block.y - 1)/Block.y);
float x = (float)(srcWidth)/(float)dstWidth;
float y = (float)(srcHeight)/(float)dstHeight;
kernel_resize<<<Grid,Block>>>(dst,dstWidth,dstHeight,dstPitch/sizeof(float),x,y);
cudaUnbindTexture(tex32f);
return 0;
}
结果(按比例缩小 2):
输入(10 x 10):
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 1 1 1 1 0 0 0
0 0 0 1 1 1 1 0 0 0
0 0 0 1 1 1 1 0 0 0
0 0 0 1 1 1 1 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
MATLAB 和 OpenCV 输出:
0 0 0 0 0
0 0.25 0.5 0.25 0
0 0.5 1 0.5 0
0 0.25 0.5 0.25 0
0 0 0 0 0
我的输出:
0 0 0 0 0
0 0 0 0 0
0 0 1 1 0
0 0 1 1 0
0 0 0 0 0