OpenCV CUDA模块设备层-----反正弦运算函数asin()

发布于:2025-06-22 ⋅ 阅读:(19) ⋅ 点赞:(0)
  • 操作系统:ubuntu22.04
  • OpenCV版本:OpenCV4.9
  • IDE:Visual Studio Code
  • 编程语言:C++11

算法描述

对一个 uchar 类型的像素值(范围 [0, 255]),先归一化到浮点范围 [0.0, 1.0],然后计算其反正弦值 asin(x),最终返回一个 float1 类型的结果。

函数原型

__device__ __forceinline__ float1 cv::cudev::asin 	( 	const uchar1 &  	a	) 	

参数

  • uchar1 CUDA 向量类型,表示一个单通道的 8 位无符号整型(等价于 unsigned char 或 uint8_t)。

代码示例


#include <opencv2/opencv.hpp>
#include <opencv2/cudev/common.hpp>
#include <opencv2/cudev/functional/functional.hpp>
#include <opencv2/cudev/util/vec_math.hpp>

__global__
void apply_asin_kernel(const uchar* input, float* output, int width, int height) {
    int x = blockIdx.x * blockDim.x + threadIdx.x;
    int y = blockIdx.y * blockDim.y + threadIdx.y;

    if (x >= width || y >= height)
        return;

    int idx = y * width + x;
    uchar raw_value = input[idx];
    float normalized = raw_value / 255.0f;

    // 确保在定义域内
    if (normalized < -1.0f) normalized = -1.0f;
    if (normalized > 1.0f) normalized = 1.0f;

    output[idx] = asinf(normalized);
}

int main() {
    // 创建测试图像(uchar类型,单通道)
    cv::Mat h_img = cv::Mat::zeros(480, 640, CV_8UC1);
    cv::randu(h_img, cv::Scalar::all(0), cv::Scalar::all(255));

    // 将输入上传到设备
    cv::cuda::GpuMat d_img;
    d_img.upload(h_img);

    // 创建输出设备内存(float1)
    cv::cuda::GpuMat d_out;
    d_out.create(d_img.size(), CV_32FC1);

    // 获取原始指针
    const uchar* d_input = d_img.ptr<uchar>();
    float* d_output = d_out.ptr<float>();

    // 设置 CUDA 线程块大小
    dim3 blockSize(16, 16);
    dim3 gridSize((d_img.cols + blockSize.x - 1) / blockSize.x,
                  (d_img.rows + blockSize.y - 1) / blockSize.y);

    // 启动核函数
    apply_asin_kernel<<<gridSize, blockSize>>>(d_input, d_output, d_img.cols, d_img.rows);

    // 下载结果到主机
    cv::Mat h_out;
    d_out.download(h_out);

    // 显示部分结果
    std::cout << "First pixel (uchar): " << (int)h_img.at<uchar>(0, 0) << std::endl;
    std::cout << "After asin (float): " << h_out.at<float>(0, 0) << std::endl;

    return 0;
}

运行结果

First pixel (uchar): 91
After asin (float): 0.364907

网站公告

今日签到

点亮在社区的每一天
去签到