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,缩短了一半