- 操作系統:ubuntu22.04
- OpenCV版本:OpenCV4.9
- IDE:Visual Studio Code
- 編程語言:C++11
算法描述
OpenCV CUDA 模塊(cudev) 中的一個仿函數(functor)生成器,用于創建一個反向二值化閾值處理函數對象。
這個函數返回一個 仿函數對象(functor),用于在 GPU 上執行反向二值化閾值處理(Threshold Binary Inverted),即:
如果像素值小于等于 thresh,則設為 maxVal;否則設為 0。
函數原型
template<typename T >
__host__ __device__ ThreshBinaryInvFunc<T> cv::cudev::thresh_binary_inv_func ( T thresh,T maxVal )
參數
- T thresh 閾值,如果像素值小于等于該值則保留最大值
- T maxVal 像素滿足條件時設置的最大值
代碼
#include <opencv2/cudev.hpp>
#include <opencv2/cudaimgproc.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>// CUDA kernel 使用 functor 對圖像進行反向二值化
template <typename T>
__global__ void thresholdInvKernel(const T* input, T* output, int numPixels,cv::cudev::ThreshBinaryInvFunc<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: 創建反向二值化函數對象auto func = cv::cudev::thresh_binary_inv_func<uchar>(128, 255);// Step 4: 啟動 kernelint blockSize = 256;int numBlocks = (numPixels + blockSize - 1) / blockSize;thresholdInvKernel<<<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("Binary Inv Threshold Result", result);cv::waitKey(0);cv::imwrite("binary_inv_result.jpg", result);// Step 7: 清理資源cudaFree(d_input);cudaFree(d_output);return 0;
}