OpenCV3.0基于CUDA的高斯模糊(滤波)实现
前言
需要:
- OpenCV3.0以上版本
编译时编译CUDA模块,即USE_CUDA
需要注意的是:
CUDA版的高斯模糊目前只支持<=siez(31,31)的高斯核。
代码:
#include <opencv2/opencv.hpp>
#include <opencv2/xfeatures2d.hpp>
#include <opencv2/cudafilters.hpp>
#include <cuda.h>
int main(){
//得到一张图片
cv::Mat src = cv::imread("../data/lena.png",0);
cv::Mat dst_image;
//变换图片的类型到CV_32FC1,与后面的GaussianFilter参数匹配
src.convertTo(dst_image, CV_32FC1);
//定义参与计算的CUDA的GpuMat
cv::cuda::GpuMat d_src_img(dst_image);
//定义一个output的GpuMat,d_src_img是input的GpuMat
cv::cuda::GpuMat gpu(d_src_img);
//host to device,将数据拷入GpuMat
d_src_img.upload(dst_image);
//CUDA高斯滤波的实现
cv::Ptr<cv::cuda::Filter> gauss = cv::cuda::createGaussianFilter(CV_32F, CV_32F, Size(11, 11), 1.5, 0, cv::BORDER_DEFAULT,-1); //创建高斯滤波器
gauss->apply(d_src_img, gpu); //高斯滤波
//承载计算完的GpuMat中的数据,需要将计算结果拷回普通的Mat
Mat test(dst_image);
//将结果从GpuMat拷回Mat
gpu.download(test);
//为了显示,将CV_32FC1转回uchar
Mat gray1;
test.convertTo(gray1,DataType<uchar>::type, 1, 0);
//显示
cv::namedWindow("test",0);
cv::imshow("test",gray1);
cv::waitKey(0);
return 0;
}
- 其中
GpuMat
在OpenCV3.0之后在cuda
命名空间下 - 其中Mat类型的转来转去,是为了配合执行和显示
d_src_img.upload(dst_image);
是将数据从host传入device。 而
gpu.download(test);