c++ - thrust::max_element() 为 2D 矩阵返回不正确的值

标签 c++ opencv thrust

我尝试使用推力从二维矩阵中找到最大元素。但是,我总是得到不正确的结果。这些代码适用于 1D 矩阵,但在使用 2D 矩阵时表现得不可预测。

我将 opencv GpuMat 用于二维矩阵。这是我的代码。我想知道是否有人遇到过同样的问题?

#include <thrust/device_ptr.h> 
#include <thrust/device_vector.h>
#include <thrust/extrema.h>
#include <iostream> 

#include <opencv2\opencv.hpp>
#include <opencv2\cuda.hpp>

using namespace std;
using namespace cv;
using namespace cv::cuda;

ushort thrust_find_max_idx(const GpuMat& in_, int* p_r_, int* p_c_){
    thrust::device_ptr<ushort> ptr((ushort*)in_.data);
    unsigned int N = in_.cols * in_.rows;
    thrust::device_vector<ushort>::iterator iter = thrust::max_element(ptr, ptr + N); //find max element
    int pos = thrust::device_pointer_cast(&(iter[0])) - ptr;
    *p_r_ = pos / in_.cols; 
    *p_c_ = pos % in_.cols;
    return *iter;
}

int main(void) 
{ 
    Mat cpu_matrix; cpu_matrix.create(10, 10, CV_16UC1);
    randu(cpu_matrix, 1, 256); //generate random sequences
    GpuMat matrix; matrix.upload(cpu_matrix);
    int r, c;
    ushort max = thrust_find_max_idx( matrix, &r, &c);
    matrix.download(cpu_matrix);    
    cout << cpu_matrix << endl; //output testing sequences
    cout << max << " r " << r << " c " << c << endl; //output max element and positions

    return 0; 
}

最佳答案

感谢罗伯特的回复,我明白了GpuMat默认情况下不会连续分配为 Mat,但幸运的是,函数 cuda::minMaxLoc()可用于快速识别 GpuMat 中的最大元素。

double max; cv::Point loc;
cv::cuda::minMaxLoc(matrix, 0, &max, 0, &loc);

关于c++ - thrust::max_element() 为 2D 矩阵返回不正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25509981/

相关文章:

c++ - 分水岭算法后边界框和圆圈过多

c++ - 使用 thrust::for_each() 调用实现 CUDA 流时访问结构的结果

c++ - 如何使用 C++ 在 Linux 中移动文件

c++ - c++ 中的 stdexcept 与异常 header

C++ 从 *.txt 文件读取数据到结构 vector

python - Y channel 的高斯模糊图像直方图

android - OpenCV4Android 类 Mat : difference between width() and rows(), 以及 height() 和 cols() 之间的类?

linux - CUDA 多设备问题,thrust::system_error

cuda - 具有 Cuda Thrust 的多个 GPU?

c++ - 将 QPixmaps 拖入 QGraphicsScene : how to avoid 'auto' not allowed in lambda parameter