在不知道类型opencv的情况下访问矩阵值
Acces Matrix value without knowing the type opencv
我正在编写一个函数,其中我需要访问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);
相关文章:
- c++, 在子类中,如何在没有对象的情况下访问父类的方法?
- 是否可以在不复制的情况下访问undered_map中的元素
- 为什么不能指向指针,在没有强制转换的情况下访问结构成员?
- 在不创建子矩阵的情况下计算C++矩阵的行列式
- 为什么可以在没有实例变量的情况下访问静态回调方法中的静态成员变量?
- 如何在不设置完整路径的情况下访问 c++ 中的资源
- 如何在 getter 的父类中初始化变量的情况下访问子类中的变量
- 在不违反严格的别名规则的情况下访问进程间共享内存中的对象
- C++ 在不打开文件的情况下访问IMAGE_OPTIONAL_HEADER64?
- 如何在不使用全局变量的情况下访问 lambda 中的变量
- C++是否提供了一种在没有范围解析运算符的情况下访问类中的类的方法?
- 是否可以超载[]运算符在不定义类的情况下访问特定的字符
- 在没有捕获列表的情况下访问 lambda 中的变量
- 如何在不注册对象的情况下访问标准项模型的数据?
- 在不破坏封装的情况下访问基类元素
- 可以在没有递归的情况下发现矩阵的决定因素
- 如何在不将类数据成员作为参数传递的情况下访问线程中的类数据成员
- 在没有2D阵列的情况下从矩阵文件中读取坐标
- 如何在没有 A 全局的情况下访问 A::member()
- 在不知道类型opencv的情况下访问矩阵值