- 操作系統:ubuntu22.04
- OpenCV版本:OpenCV4.9
- IDE:Visual Studio Code
- 編程語言:C++11
算法描述
OpenCV 的 CUDA 模塊(cudev) 中的一個仿函數生成器,用于創建一個 “大于閾值設為零” 的圖像處理函數對象。
這個函數返回一個 仿函數對象(functor),用于在 GPU 上執行如下操作:
如果像素值大于 thresh,則設置為 0;否則保留原值不變。
函數原型
__host__ __device__ ThreshToZeroInvFunc<T> cv::cudev::thresh_to_zero_inv_func ( T thresh )
參數
- T thresh 閾值,如果像素值大于該值,則設置為 0
代碼
#include <opencv2/cudev.hpp>
#include <opencv2/cudaimgproc.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>// CUDA kernel 使用 functor 對圖像進行 "大于閾值設為 0" 處理
template <typename T>
__global__ void toZeroInvKernel(const T* input, T* output, int numPixels,cv::cudev::ThreshToZeroInvFunc<T> func) {int idx = blockIdx.x * blockDim.x + threadIdx.x;if (idx < numPixels) {output[idx] = func(input[idx]);}
}int main() {// Step 1: 讀取圖像并轉為灰度圖cv::Mat bgr = cv::imread("/media/dingxin/data/study/OpenCV/sources/images/Lenna.png", cv::IMREAD_COLOR);if (bgr.empty()) {std::cerr << "Failed to load image!" << std::endl;return -1;}cv::Mat src;cv::cvtColor(bgr, src, cv::COLOR_BGR2GRAY); // 灰度圖int width = src.cols;int height = src.rows;int numPixels = width * height;// Step 2: 分配 GPU 內存uchar* d_input, *d_output;cudaMalloc(&d_input, numPixels * sizeof(uchar));cudaMalloc(&d_output, numPixels * sizeof(uchar));cudaMemcpy(d_input, src.data, numPixels * sizeof(uchar), cudaMemcpyHostToDevice);// Step 3: 創建 "大于閾值設為 0" 的函數對象auto func = cv::cudev::thresh_to_zero_inv_func<uchar>(128);// Step 4: 啟動 kernelint blockSize = 256;int numBlocks = (numPixels + blockSize - 1) / blockSize;toZeroInvKernel<<<numBlocks, blockSize>>>(d_input, d_output, numPixels, func);// Step 5: 下載結果cv::Mat result(height, width, CV_8U);cudaMemcpy(result.data, d_output, numPixels * sizeof(uchar), cudaMemcpyDeviceToHost);// Step 6: 顯示和保存結果cv::imshow("original image", bgr);cv::imshow("ToZero Inv Threshold Result", result);cv::waitKey(0);cv::imwrite("tozero_inv_result.jpg", result);// Step 7: 清理資源cudaFree(d_input);cudaFree(d_output);return 0;
}