OpenCV CUDA模块设备层-----创建一个“常量指针访问器” 的工具函数constantPtr()

发布于:2025-06-26 ⋅ 阅读:(23) ⋅ 点赞:(0)
  • 操作系统:ubuntu22.04
  • OpenCV版本:OpenCV4.9
  • IDE:Visual Studio Code
  • 编程语言:C++11

算法描述

在 CUDA 设备端模拟一个“指向常量值”的虚拟指针访问器,使得你可以像访问数组一样访问一个固定值。
这在某些核函数中非常有用,例如当你希望将一个标量值作为图像或矩阵来使用时(如与卷积核、滤波器结合)。

函数原型

__host__ ConstantPtr<T> cv::cudev::constantPtr 	( 	T  	value	) 	

参数

  • value T 要封装为常量访问器的值。

使用场景举例

  • 在 CUDA 核函数中将一个标量值当作“全图常量图像”使用;
  • 与 filter2D, convolve, 自定义卷积核等结合使用;
  • 简化逻辑,统一接口:无论输入是真实图像还是常量图像,都可调用相同的访问器接口。

代码示例


#include <opencv2/core/cuda.hpp>
#include <opencv2/cudev/ptr2d/constant.hpp>
#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv::cudev;

// 核函数:使用 constantPtr 访问一个常量图像
__global__ void fillKernel(const ConstantPtr<uchar> src,
                           uchar* dst,
                           int width,
                           int height) {
    int x = blockIdx.x * blockDim.x + threadIdx.x;
    int y = blockIdx.y * blockDim.y + threadIdx.y;

    if (x >= width || y >= height)
        return;

    // 无论坐标是什么,都返回常量值
    dst[y * width + x] = src(y, x);
}

int main() {
    const int width = 640;
    const int height = 480;
    const uchar constantValue = 128;

    // 创建 GPU 图像
    cv::cuda::GpuMat d_dst(height, width, CV_8UC1);

    // 使用 constantPtr 封装一个常量值
    auto constAccessor = constantPtr(constantValue);

    dim3 block(16, 16);
    dim3 grid((width + block.x - 1) / block.x,
              (height + block.y - 1) / block.y);

    fillKernel<<<grid, block>>>(constAccessor, d_dst.ptr<uchar>(),
                                width, height);

    // 下载结果
    cv::Mat h_dst;
    d_dst.download(h_dst);

    // 显示图像信息
    std::cout << "Image size: " << h_dst.size() << ", type: " << h_dst.type() << std::endl;
    std::cout << "First pixel value: " << static_cast<int>(h_dst.at<uchar>(0, 0)) << std::endl;

    // 保存图像
    cv::imwrite("constant_image.png", h_dst);
    std::cout << "Saved image as 'constant_image.png'" << std::endl;

    return 0;
}

运行结果

Image size: [640 x 480], type: 0
First pixel value: 128
Saved image as 'constant_image.png'


网站公告

今日签到

点亮在社区的每一天
去签到