最近刚接触CUDA,先写一些简单的示例练习下。
在图像处理中,三通道彩色图像BGR到灰度图Gray,常见的一般有两种计算方式,一种是基于浮点数计算,一种是基于性能优化的通过移位的整数计算。
浮点数计算公式为: gray = 0.1140 * B + 0.5870 * G + 0.2989 * R
整数计算公式为: gray = (1868 * B + 9617 * G + 4899 * R) >> 14 ,1868从二进制的角度看,向右移位14位,相当于,以此类推。
下面的代码主要参考[2]进行修改得到:
头文件:funset.hpp
#include <cuda_runtime.h> // For the CUDA runtime routines (prefixed with "cuda_")
#include <device_launch_parameters.h>
#include <cstdlib>
#include <vector>
int bgr2gray_cpu(const unsigned char* src, int width, int height, unsigned char* dst);
int bgr2gray_gpu(const unsigned char* src, int width, int height, unsigned char* dst);
基于CPU的BRG2GRAY:bgr2gray.cpp
#include "funset.hpp"
int bgr2gray_cpu(const unsigned char* src, int width, int height, unsigned char* dst)
{
const int R2Y{ 4899 }, G2Y{ 9617 }, B2Y{ 1868 }, yuv_shift{ 14 };
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
dst[y * width + x] = (unsigned char)((src[y*width * 3 + 3 * x + 0] * B2Y +
src[y*width * 3 + 3 * x + 1] * G2Y + src[y*width * 3 + 3 * x + 2] * R2Y) >> yuv_shift);
}
}
return 0;
}
基于GPU的BRG2GRAY:bgr2gray.cu
#include "funset.hpp"
/* __global__: 函数类型限定符;在GPU设备上运行;在主机端CPU调用,计算能力3.2及以上可以在
设备端调用;声明的函数的返回值必须是void类型;对此类型函数
CUDA实现BGR2GRAY及性能测试

最低0.47元/天 解锁文章
1万+

被折叠的 条评论
为什么被折叠?



