- 操作系統:ubuntu22.04
- OpenCV版本:OpenCV4.9
- IDE:Visual Studio Code
- 編程語言:C++11
算法描述
OpenCV 的 CUDA 設備函數(device function),用于在 GPU 上計算一個 uchar4 類型向量的平方根,并返回一個 float4 類型的結果。
這個函數通常出現在 OpenCV 的 CUDA 加速圖像處理代碼中,例如:
- 圖像歸一化(Normalization)
- 色彩空間轉換
- 卷積、濾波等操作中涉及數值穩定性的平方根計算
它被設計為在 CUDA kernel 中高效使用,適用于需要對圖像像素批量執行數學運算的高性能場景。
函數原型
__device__ __forceinline__ float4 cv::cudev::sqrt(const uchar4 &a)
參數
- const uchar4 &a 輸入參數是一個 uchar4 類型的常量引用(即 4 個無符號字符)
代碼
#include <opencv2/opencv.hpp>
#include <opencv2/cudaimgproc.hpp>
#include <opencv2/cudev.hpp>
#include <iostream>__global__ void sqrtKernel(const uchar4* input, float4* output, int numPixels) {int idx = blockIdx.x * blockDim.x + threadIdx.x;if (idx < numPixels) {output[idx] = cv::cudev::sqrt(input[idx]);}
}int main() {// 讀取圖像(RGBA 格式)cv::Mat bgr = cv::imread("/media/dingxin/data/study/OpenCV/sources/images/img0.jpg");if (bgr.empty()) {std::cerr << "Failed to load image!" << std::endl;return -1;}// 轉換為 RGBAcv::Mat src;cv::cvtColor(bgr, src, cv::COLOR_BGR2BGRA);int width = src.cols;int height = src.rows;int numPixels = width * height;// 將輸入圖像上傳到 GPUuchar4* d_input;cudaMalloc(&d_input, numPixels * sizeof(uchar4));cudaMemcpy(d_input, src.ptr<uchar4>(), numPixels * sizeof(uchar4), cudaMemcpyHostToDevice);// 分配輸出內存float4* d_output;cudaMalloc(&d_output, numPixels * sizeof(float4));// 啟動 kernelint blockSize = 256;int numBlocks = (numPixels + blockSize - 1) / blockSize;sqrtKernel<<<numBlocks, blockSize>>>(d_input, d_output, numPixels);// 下載結果回 CPUcv::Mat result(height, width, CV_32FC4);cudaMemcpy(result.ptr<float4>(), d_output, numPixels * sizeof(float4), cudaMemcpyDeviceToHost);// 顯示或保存結果(例如將每個通道 clamp 到 [0,1] 并歸一化顯示)cv::Mat display;cv::normalize(result, display, 0, 1, cv::NORM_MINMAX, CV_32F);cv::imshow("Result", display);cv::waitKey(0);// 清理資源cudaFree(d_input);cudaFree(d_output);return 0;
}