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;
}

运行结果

相关推荐
中杯可乐多加冰1 小时前
OpenClaw到底能做什么?有什么用?先装这几个实用的Skills
人工智能
千寻girling1 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
aircrushin3 小时前
从春晚看分布式实时协同算法与灵巧手工程实现
人工智能·机器人
恋猫de小郭3 小时前
Apple 的 ANE 被挖掘,AI 硬件公开,宣传的 38 TOPS 居然是"数字游戏"?
前端·人工智能·ios
银河系搭车客指南4 小时前
AI Agent 的失忆症:我是怎么给它装上"第二个大脑"的
人工智能
张拭心4 小时前
春节后,有些公司明确要求 AI 经验了
android·前端·人工智能
我的username4 小时前
极致简单的openclaw安装教程
人工智能
小锋java12344 小时前
【技术专题】嵌入模型与Chroma向量数据库 - Chroma 集合操作
人工智能
七月丶4 小时前
别再手动凑 PR 了:这个 AI Skill 会按仓库习惯自动建分支、拆提交、提 PR
人工智能·设计模式·程序员
用户5191495848455 小时前
CVE-2024-10793 WordPress插件权限提升漏洞利用演示
人工智能·aigc