- 操作系統: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'