我正在编写一个函数,在该函数中我需要访问 a 的元素Mat,但该函数可以接收Mat不同的类型。所以,如果我有:
filtered.at<TypeofMat>(i) = (typeofmat) somevalue;
Run Code Online (Sandbox Code Playgroud)
我只是filtered.at<myMat.type()>(i)想到做这样的事情,但显然这不起作用,因为type返回一个int
我被卡住了,有人能给点光吗?
您可以将源矩阵转换为双精度矩阵(类型CV_64F)。这样你就不会因为投射而丢失任何数据。然后你可以像往常一样处理这个矩阵,因为你知道它的类型。最后一步是将目标图像转换回源类型。
不过,您需要知道矩阵的通道数。ACV_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;
}
Run Code Online (Sandbox Code Playgroud)
这种方法也有替代方案: