OpenCV CUDA模块设备层-----二值化阈值操作函数thresh_binary_func()
- 操作系统:ubuntu22.04
- OpenCV版本:OpenCV4.9
- IDE:Visual Studio Code
- 编程语言:C++11
算法描述
OpenCV 的 CUDA 模块(cudev) 中的一个设备和主机通用函数(host/device function),用于创建一个二值化阈值操作函数对象(functor)。
这个函数返回一个仿函数(functor),用于在 GPU 上执行 二值化阈值处理(Threshold Binary),即:
如果像素值大于 thresh,则设为 maxVal;否则设为 0。
函数原型
__host__ __device__ ThreshBinaryFunc<T> cv::cudev::thresh_binary_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 thresholdKernel(const T* input, T* output, int numPixels,cv::cudev::ThreshBinaryFunc<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_func<uchar>(128, 255);// Step 4: 启动 kernelint blockSize = 256;int numBlocks = (numPixels + blockSize - 1) / blockSize;thresholdKernel<<<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 Threshold Result", result);cv::waitKey(0);cv::imwrite("binary_result.jpg", result);// Step 7: 清理资源cudaFree(d_input);cudaFree(d_output);return 0;
}