我正在制作一个初学者CUDA程序,该程序基本上使用OpenCV对输入的灰度图像进行降采样。经过测试,它可以很好地处理8位灰度图像,但是当输入16位灰度图像时,它会给出嘈杂的降采样图像,图像的右半部分为空白。以下是我编写的代码。
提供了示例输入和输出图像
和
我的main.cpp代码将图像加载到Mat中:
int main()
{
cv::Mat im1 = cv::imread("test.png", -1);
std::string output_file = "resultout.png";
binFilter(im1, output_file);
return 0;
}
我的CUDA内核代码:
__global__ void binCUDAKernel(unsigned char *input, unsigned char *output, int binDim, int outputWidth, int outputHeight, int inputWstep, int outputWstep, int nChannels)
{
int outXind = blockIdx.x * blockDim.x + threadIdx.x;
int outYind = blockIdx.y * blockDim.y + threadIdx.y;
if ((outXind < outputWidth) && (outYind < outputHeight)) // Only run threads in output image coordinate range
{
if (nChannels == 1) // Test only for greyscale images
{
// Calculate x & y index of input binned pixels corresponding to current output pixel
int inXstart = outXind * binDim;
int inYstart = outYind * binDim;
// Perform binning on identified input pixels
float sum = 0;
for (int binY = inYstart; binY < (inYstart + binDim); binY++) {
for (int binX = inXstart; binX < (inXstart + binDim); binX++) {
int input_tid = binY * inputWstep + binX;
sum += input[input_tid];
}
}
// Establish output thread index in current output pixel index
int output_tid = outYind * outputWstep + outXind;
// Assign binned pixel value to output pixel
output[output_tid] = static_cast<unsigned short>(sum / (binDim*binDim));
}
}
}
我的CPU代码:
void binFilter(const cv::Mat input, std::string output_file)
{
// 2X2 binning
int binDim = 2;
// Create blank output image & calculate size of input and output
cv::Size outsize(input.size().width / binDim, input.size().height / binDim);
cv::Mat output(outsize, input.type());
const int inputBytes = input.step * input.rows;
const int outputBytes = output.step * output.rows;
// Allocate memory in device
unsigned char *d_input, *d_output;
gpuErrchk(cudaMalloc<unsigned char>(&d_input, inputBytes));
gpuErrchk(cudaMalloc<unsigned char>(&d_output, outputBytes));
// Copy input image to device
gpuErrchk(cudaMemcpy(d_input, input.ptr(), inputBytes, cudaMemcpyHostToDevice));
// Configure size of block and grid
const dim3 block(16, 16);
const dim3 grid((output.cols + block.x - 1) / block.x, (output.rows + block.y - 1) / block.y); // Additional block for rounding up
// Execute kernel
binCUDAKernel <<<grid, block>>> (d_input, d_output, binDim, output.cols, output.rows, input.step, output.step, input.channels());
gpuErrchk(cudaPeekAtLastError());
// Wait for all threads to finish
//gpuErrchk(cudaDeviceSynchronize());
// Copy output image from device back to host (cudaMemcpy is a blocking instruction)
gpuErrchk(cudaMemcpy(output.ptr(), d_output, outputBytes, cudaMemcpyDeviceToHost));
// Free device memory
gpuErrchk(cudaFree(d_input));
gpuErrchk(cudaFree(d_output));
// Write image to specified output_file path
cv::imwrite(output_file, output);
}
我怀疑这可能是某种数据类型不匹配,但我无法弄清楚。
答案 0 :(得分:2)
首先,为了处理16位图像,必须将像素数据解释为16位宽的数据类型,该数据类型可能为unsigned short
或short
。请记住,我们只需要将图像数据解释为unsigned short
类型;不用打字为此,我们仅将图像数据指针转换为所需的类型,如以下示例所示:
unsigned short* ptr16 = reinterpret_cast<unsigned short*>(im1.ptr());
由于上述步骤,我们还必须为16位数据类型创建一个单独的内核。我们可以通过将内核定义为C ++模板来巧妙地做到这一点。 因此内核可能如下所示:
template<typename T>
__global__ void binCUDAKernel(T *input, T *output, int binDim, int outputWidth, int outputHeight, int inputWstep, int outputWstep, int nChannels)
{
int outXind = blockIdx.x * blockDim.x + threadIdx.x;
int outYind = blockIdx.y * blockDim.y + threadIdx.y;
if ((outXind < outputWidth) && (outXind > outputWidth/2) && (outYind < outputHeight)) // Only run threads in output image coordinate range
{
if (nChannels == 1) // Test only for greyscale images
{
// Calculate x & y index of input binned pixels corresponding to current output pixel
int inXstart = outXind * binDim;
int inYstart = outYind * binDim;
// Perform binning on identified input pixels
float sum = 0;
for (int binY = inYstart; binY < (inYstart + binDim); binY++) {
for (int binX = inXstart; binX < (inXstart + binDim); binX++) {
int input_tid = binY * inputWstep + binX;
sum += float(input[input_tid]);
}
}
// Establish output thread index in current output pixel index
int output_tid = outYind * outputWstep + outXind;
// Assign binned pixel value to output pixel
output[output_tid] = static_cast<T>(sum / (binDim*binDim));
}
}
}
在使用自定义CUDA内核处理OpenCV Mat的过程中,另一个重要的问题是,图像步长必须除以数据类型的大小(以字节为单位)。对于16位图像,单个像素的大小为16位(2字节),因此内核中使用的步骤必须除以2。请记住,原始步骤不应修改。应该只对作为内核参数传递的步长值进行除法。
结合以上修复程序,最终的CPU代码可能如下所示:
void binFilter(const cv::Mat input, std::string output_file)
{
// 2X2 binning
int binDim = 2;
// Create blank output image & calculate size of input and output
cv::Size outsize(input.size().width / binDim, input.size().height / binDim);
cv::Mat output(outsize, input.type());
const int inputBytes = input.step * input.rows;
const int outputBytes = output.step * output.rows;
// Allocate memory in device
unsigned char *d_input, *d_output;
gpuErrchk(cudaMalloc<unsigned char>(&d_input, inputBytes));
gpuErrchk(cudaMalloc<unsigned char>(&d_output, outputBytes));
// Copy input image to device
gpuErrchk(cudaMemcpy(d_input, input.ptr(), inputBytes, cudaMemcpyHostToDevice));
// Configure size of block and grid
const dim3 block(16, 16);
const dim3 grid((output.cols + block.x - 1) / block.x, (output.rows + block.y - 1) / block.y); // Additional block for rounding up
int depth = input.depth();
// Execute kernel
if (input.depth() == CV_16U)
{
typedef unsigned short t16;
t16* input16 = reinterpret_cast<t16*>(d_input);
t16* output16 = reinterpret_cast<t16*>(d_output);
int inputStep16 = input.step / sizeof(t16);
int outputStep16 = output.step / sizeof(t16);
binCUDAKernel <t16> <<<grid, block>>> (input16, output16, binDim, output.cols, output.rows, inputStep16, outputStep16, input.channels());
}
else
{
binCUDAKernel <unsigned char> <<<grid, block>>> (d_input, d_output, binDim, output.cols, output.rows, input.step, output.step, input.channels());
}
gpuErrchk(cudaPeekAtLastError());
// Wait for all threads to finish
//gpuErrchk(cudaDeviceSynchronize());
// Copy output image from device back to host (cudaMemcpy is a blocking instruction)
gpuErrchk(cudaMemcpy(output.ptr(), d_output, outputBytes, cudaMemcpyDeviceToHost));
// Free device memory
gpuErrchk(cudaFree(d_input));
gpuErrchk(cudaFree(d_output));
// Write image to specified output_file path
cv::imwrite(output_file, output);
}
由于合并算法的逻辑,输出图像中的噪声似乎引入了混叠。例如,它与使用最近邻居方法对图像重新采样非常相似。
上面提到的计算像素的内存地址的方法是没有记载的,只是直觉的结果,因此似乎有点不合常规。 OpenCV和其他库使用的另一种方法避免了图像步骤划分的混乱。给定一个像素的x和y索引,操作如下:
unsigned char*
)。unsigned short*
)。使用此方法,我们可以如下计算灰度图像的像素存储地址:
template<typename T>
T* getPixelAddress(unsigned char* data, int x, int y, int step)
{
T* row = (T*)((unsigned char*)(data) + y * step);
return row + x;
}
在上述方法中,步长值是原始值,没有任何除法。