在不知道类型opencv的情况下访问矩阵值

Acces Matrix value without knowing the type opencv

本文关键字:情况下 访问矩阵 opencv 不知道 类型      更新时间:2023-10-16

我正在编写一个函数,其中我需要访问Mat的元素,但该函数可以接收不同类型的Mat。因此,如果我输入:

filtered.at<TypeofMat>(i) = (typeofmat) somevalue;

我只想到做这样的事情filtered.at<myMat.type()>(i),但显然这不起作用,因为type返回int

我被卡住了,有人能给点光吗?

可以将源矩阵转换为double类型的矩阵(类型为CV_64F)。这样,您就不会因为强制转换而丢失任何数据。然后你可以像往常一样处理这个矩阵,因为你知道它的类型。最后一步是将目标图像转换回源类型。

但是,您需要知道矩阵的通道数。CV_assert将确保您正在使用正确的类型。

#include <opencv2/opencv.hpp>
using namespace cv;
void foo(const Mat& src, Mat& dst)
{
    // Assert number of channels
    CV_Assert(src.channels() == 3);
    // Convert to CV64F
    Mat3d _src, _dst;
    src.convertTo(_src, CV_64F);
    _dst.create(_src.size());
    // Work on _src and _dst (you know the type)
    _dst(0,0) = _src(0,0) + Vec3d(1,2,3);
    // Convert _dst to src type
    _dst.convertTo(dst, src.type());
}
int main()
{
    Mat3b img(10,10,Vec3b(0,0,0));
    Mat res;
    foo(img, res);
    // res will be CV_8UC3
    return 0;
}

还有其他方法:

  • 创建一个模板函数并调用适当的专门化。看到
  • 处理原始指针。看到
  • 只使用OpenCV函数,正确处理每种类型。在这里看到的。如果可以,这通常是最好的选择。

如果有可能,让接收openCV Mat的函数成为模板函数:

void f<typename T>(const Mat& m)
{
    (void) m.at<T>(0, 0);
}

这样用:

Mat m1/* ... */;
m1.at<int>(0, 0) = 0;
f<int>(m);