C++ 如何通过另一个具有位置(索引)的mat访问opencv中的矩阵数据

C++ 如何通过另一个具有位置(索引)的mat访问opencv中的矩阵数据,c++,opencv,mat,C++,Opencv,Mat,假设我有一个称为B的索引(位置)矩阵,我们可以说这个矩阵的维数为1 x 100,我们假设有另一个矩阵,称为a,充满了与B相同维数的数据。 现在,我将使用B访问A的数据。通常我会创建一个for循环,并为B的每个元素获取A的正确元素。对于最复杂的站点,我将编写以下代码: for(int i=0; i < B.cols; i++){ int index = B.at<int>(0, i); std::cout<<A.at<int>(0, ind

假设我有一个称为B的索引(位置)矩阵,我们可以说这个矩阵的维数为
1 x 100
,我们假设有另一个矩阵,称为a,充满了与B相同维数的数据。 现在,我将使用B访问A的数据。通常我会创建一个for循环,并为B的每个元素获取A的正确元素。对于最复杂的站点,我将编写以下代码:

for(int i=0; i < B.cols; i++){
    int index = B.at<int>(0, i);
    std::cout<<A.at<int>(0, index)<<std:endl;
}
for(int i=0;i
下面我给出了一个关于重映射算法工作原理的基本示例;请注意,在这个示例中我不处理边界条件,但
cv::remap
处理边界条件-它允许您使用镜像、钳制等来指定索引超过图像尺寸时会发生什么情况。我也不显示如何进行插值;请检查
cv::重新映射我上面链接的文档

如果要使用重新映射,可能必须将索引转换为浮点;还必须引入另一个索引数组,该数组应该很简单(都等于0)如果你的图像是一维的。如果这表现出性能问题,我建议你自己实现一维重映射。当然,在优化之前先进行基准测试

有关所有详细信息,请查看文档,其中涵盖了使用te算法所需了解的所有内容

cv::Mat<float> remap_example(cv::Mat<float> image, 
                             cv::Mat<float> positions_x, 
                             cv::Mat<float> positions_y)
{
   // sizes of positions arrays must be the same
   int size_x = positions_x.cols;
   int size_y = positions_x.rows;
   auto out = cv::Mat<float>(size_y, size_x);

   for(int y = 0; y < size_y; ++y)
     for(int x = 0; x < size_x; ++x)
     {
       float ps_x = positions_x(x, y);
       float ps_y = positions_y(x, y);

       // use interpolation to determine intensity at image(ps_x, ps_y),
       // at this point also handle border conditions 
       // float interpolated = bilinear_interpolation(image, ps_x, ps_y);

       out(x, y) = interpolated;
      }

return out;
}
cv::Mat重新映射\u示例(cv::Mat图像,
cv::垫位置,
cv::垫位置(y)
{
//位置数组的大小必须相同
int size_x=位置_x.cols;
int size_y=位置_x.行;
自动输出=cv::Mat(尺寸y,尺寸x);
对于(int y=0;y
一种快速方法是对A(数据)和B(索引)使用指针

const int*pA=A.ptr(0);
常数int*pIndexB=B.ptr(0);
整数和=0;
对于(int i=0;i
注意:小心像素类型,在这种情况下(正如您在代码中所写的)是int

注2:对每个访问点使用cout将使优化无效

注3:在本文中,Satya比较了四种像素访问方法和“foreach”:

const int* pA = A.ptr<int>(0);
const int* pIndexB = B.ptr<int>(0);
int sum = 0;
for(int i = 0; i < Bi.cols; ++i)
{
    sum += pA[*pIndexB++];
}