OpenCV CUDA模块设备层-----反向二值化阈值处理函数thresh_binary_inv_func()

  • 操作系统:ubuntu22.04
  • OpenCV版本:OpenCV4.9
  • IDE:Visual Studio Code
  • 编程语言:C++11

算法描述

OpenCV CUDA 模块(cudev) 中的一个仿函数(functor)生成器,用于创建一个反向二值化阈值处理函数对象。

这个函数返回一个 仿函数对象(functor),用于在 GPU 上执行反向二值化阈值处理(Threshold Binary Inverted),即:

如果像素值小于等于 thresh,则设为 maxVal;否则设为 0。

函数原型

cpp 复制代码
template<typename T >
__host__ __device__ ThreshBinaryInvFunc<T> cv::cudev::thresh_binary_inv_func 	( 	T  	thresh,
		T  	maxVal 
	) 		

参数

  • T thresh 阈值,如果像素值小于等于该值则保留最大值
  • T maxVal 像素满足条件时设置的最大值

代码

cpp 复制代码
#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: 启动 kernel
    int 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;
}

运行结果

相关推荐
小雷FansUnion1 小时前
深入理解MCP架构:智能服务编排、上下文管理与动态路由实战
人工智能·架构·大模型·mcp
资讯分享周1 小时前
扣子空间PPT生产力升级:AI智能生成与多模态创作新时代
人工智能·powerpoint
叶子爱分享2 小时前
计算机视觉与图像处理的关系
图像处理·人工智能·计算机视觉
鱼摆摆拜拜2 小时前
第 3 章:神经网络如何学习
人工智能·神经网络·学习
一只鹿鹿鹿2 小时前
信息化项目验收,软件工程评审和检查表单
大数据·人工智能·后端·智慧城市·软件工程
张较瘦_2 小时前
[论文阅读] 人工智能 | 深度学习系统崩溃恢复新方案:DaiFu框架的原位修复技术
论文阅读·人工智能·深度学习
cver1232 小时前
野生动物检测数据集介绍-5,138张图片 野生动物保护监测 智能狩猎相机系统 生态研究与调查
人工智能·pytorch·深度学习·目标检测·计算机视觉·目标跟踪
学技术的大胜嗷2 小时前
离线迁移 Conda 环境到 Windows 服务器:用 conda-pack 摆脱硬路径限制
人工智能·深度学习·yolo·目标检测·机器学习
还有糕手2 小时前
西南交通大学【机器学习实验10】
人工智能·机器学习
江瀚视野2 小时前
百度文心大模型4.5系列正式开源,开源会给百度带来什么?
人工智能