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。

函数原型


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: 启动 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;
}

运行结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

村北头的码农

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值