我正在进行一个小型图像处理项目。我想运行一个CUDA程序,做图像减法。所以你有一个图像背景和一个背景相同但上面有其他东西的图像。一旦你把减去图像,你就会得到剩下的。这两张图片的尺寸都是480*360,我的gpu是GTX780。我的程序抛出一个错误./main': free(): invalid next size (normal): 0x000000000126bd70 ***
Aborted (core dumped)
,并且输出图像是错误的。我一直在绞尽脑汁解决这个问题。这是代码:
内核:
__global__ void add(unsigned char* a, unsigned char* b, unsigned char* c, int numCols, int numWidth) {
int i = blockIdx.x * blockDim.x + threadIdx.x; //Column
int j = blockIdx.y * blockDim.y + threadIdx.y; //Row
if(i < numWidth && j < numCols)
{
int idx = j * numCols + i;
c[idx] = b[idx] - a[idx];
}
}
主要功能:
int main() {
CImg<unsigned char> img1("1.bmp");
CImg<unsigned char> img2("2.bmp");
//both images have the same size
int width = img1.width();
int height = img1.height();
int size = width * height * 3; //both images of same size
dim3 blockSize(16, 16, 1);
dim3 gridSize((width + blockSize.x - 1) / blockSize.x, (height + blockSize.y - 1) / blockSize.y, 1);
unsigned char *dev_a, *dev_b, *dev_c;
cudaMalloc((void**)&dev_a, size * (sizeof(unsigned char)));
cudaMalloc((void**)&dev_b, size * (sizeof(unsigned char)));
cudaMalloc((void**)&dev_c, size * (sizeof(unsigned char)));
cudaMemcpy(dev_a, img1, size * (sizeof(unsigned char)), cudaMemcpyHostToDevice);
cudaMemcpy(dev_b, img2, size * (sizeof(unsigned char)), cudaMemcpyHostToDevice);
add<<<gridSize, blockSize>>>(dev_a, dev_b, dev_c, height, width);
cudaMemcpy(img2, dev_c, size * (sizeof(unsigned char)), cudaMemcpyDeviceToHost);
img2.save("out.bmp");
cudaFree(dev_a);
cudaFree(dev_b);
cudaFree(dev_c);
return 0;
}
图像已加载CImg库。
问题在于主机代码中cimg容器的使用不正确。根据文档,图像数据指针是通过data()
方法访问的,这意味着主机代码中的cudaMemcpy
调用应提供img1.data()
和img2.data()
。
[这个答案是从评论中收集的,并作为社区wiki条目添加]