opencv-cuda开发(3)自定义cuda核函数实现RGB图像转灰度图像和背景差分批处理

opencv-cuda开发(2)自定义RGB图像转灰度图像批处理加速_不爱吃糖的胖子的博客-CSDN博客

在这篇文章的基础上,加入背景差分

读取一张背景图片,上传GPU,在cuda核函数内差分,然后输出为视频文件

贴部分代码和处理时间

    // 读取背景图像并将数据拷贝到GPU上
    cv::Mat background_image = cv::imread("background.png", cv::IMREAD_GRAYSCALE);
    unsigned char* background_image_dev;

    cudaMalloc(&background_image_dev, width * height);
    cudaMemcpy(background_image_dev, background_image.data, width * height, cudaMemcpyHostToDevice);

求差的绝对值 

output[y * width + x] = abs(output[y * width + x] - background[y * width + x]); // 去除背景

背景图只有一张图片,所以在批处理里不能加偏移

void process_frames(const unsigned char* dev_input, unsigned char* dev_output, unsigned char* dev_input_background, int width, int height, int num_frames)
{
    dim3 threadsPerBlock(8,125); // 8x128个线程块
    dim3 numBlocks((width + threadsPerBlock.x - 1) / threadsPerBlock.x, (height + threadsPerBlock.y - 1) / threadsPerBlock.y);

    for (int frame = 0; frame < num_frames; ++frame)
    {
        rgb_to_gray_and_bg_subtraction <<<numBlocks, threadsPerBlock >>> (dev_input + frame * width * height * 3, dev_output + frame * width * height, dev_input_background, width, height);
    }

    cudaDeviceSynchronize();
}

批处理1000帧速度74ms,比纯灰度处理增加了8ms 

 检查输出视频,结果和CPU处理一致


换了一台3060的显卡的电脑试了下这个程序,GPU处理部分的时间为34ms,缩短了一半

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值