opencv3.3 CUDA 初学实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | //swap.cu #include "cuda_runtime.h" #include "device_launch_parameters.h" #include <opencv2/core/cuda_devptrs.hpp> using namespace cv; using namespace cv::gpu; //自定义内核函数 __global__ void swap_rb_kernel( const PtrStepSz<uchar3> src,PtrStep<uchar3> dst) { int x = threadIdx.x + blockIdx.x * blockDim.x; int y = threadIdx.y + blockIdx.y * blockDim.y; if (x < src.cols && y < src.rows) { uchar3 v = src(y,x); dst(y,x) = make_uchar3(v.z,v.y,v.x); } } extern "C" void swap_rb_caller( const PtrStepSz<uchar3>& src,PtrStep<uchar3> dst,cudaStream_t stream) { dim3 block(32,8); dim3 grid((src.cols + block.x - 1)/block.x,(src.rows + block.y - 1)/block.y); swap_rb_kernel<<<grid,block,0,stream>>>(src,dst); if (stream == 0) cudaDeviceSynchronize(); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | //swap.cpp #include <opencv2/gpu/gpu.hpp> #include <opencv2/gpu/stream_accessor.hpp> using namespace cv; using namespace cv::gpu; extern "C" void swap_rb_caller( const PtrStepSz<uchar3>& src,PtrStep<uchar3> dst,cudaStream_t stream); extern "C" void swap_rb( const GpuMat& src,GpuMat& dst,Stream& stream = Stream::Null()) { CV_Assert(src.type() == CV_8UC3); dst.create(src.size(),src.type()); cudaStream_t s = StreamAccessor::getStream(stream); swap_rb_caller(src,dst,s); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | //main.cpp #include <iostream> #include <opencv2/opencv.hpp> #include <opencv2/gpu/gpu.hpp> #pragma comment(lib,"opencv_gpu2410d.lib") #pragma comment(lib,"opencv_core2410d.lib") #pragma comment(lib,"opencv_highgui2410d.lib") using namespace cv; using namespace cv::gpu; extern "C" void swap_rb( const GpuMat& src,GpuMat& dst,Stream& stream = Stream::Null()); int main() { Mat image = imread( "lena.jpg" ); imshow( "src" ,image); GpuMat gpuMat,output; gpuMat.upload(image); swap_rb(gpuMat,output); output.download(image); imshow( "gpu" ,image); getchar(); waitKey(0); return 0; } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】