gpt4 book ai didi

c++ - 如何在 opencv c++ 中为不同的 Matrix 类型编写方法而不明确指定 Mat 类型

转载 作者:太空宇宙 更新时间:2023-11-03 22:01:12 25 4
gpt4 key购买 nike

我的问题可能在 Stackoverflow 的某个地方,我找不到,如果是的话,你能给我链接吗。

基本上,我想编写一个可用于所有矩阵类型的方法。我的方法如下:

Mat my_func(Mat in){
Mat out(in.rows, in.cols, in.type());
for(int i =0; i < x; i++)
for(int j =0; j < x; j++)
out.at<in.type()>(i,j) = in.at<in.type()>(j,i); //this is just an example,
//consider that I need to use
//out.at<in.type()>(i,j) part
}

out.at<in.type()>(i,j)给出错误,因为它不接受 <in.type> , 它需要 <double>, <float>等等

我解决了这个问题

if(in.type() == 5)
out.at<float>(i,j) = //do something for float
else if (in.type() == 6)
out.at<double>(i,j) = //do something for double

应该有更好的方法,但是没找到。我搜索了与 typedef 相关的内容但我无法从我的发现中了解太多。

请注意:in.type() = 5表示名为 in 的 Matrix是 mat of floats , 同样 6mat of doubles .

提前致谢

最佳答案

m.at<type>(i,j)是模板表达式。编译器必须在编译时解析类型。

所以,任何在运行时作弊的尝试,如 m1.at<m2.type()>(i,j)注定了。

好消息是,还有模板 Mat,例如 Mat_<float>您可以像 m(i,j) 一样访问它(没有讨厌的模板括号)。

因此,您的示例代码甚至可能如下所示:

template<class T>
Mat_<T> my_func(Mat_<T> in){
Mat_<T> out(in.cols, in.rows);
for(int i =0; i < in.cols; i++)
for(int j =0; j < in.rows; j++)
out(j,i) = in(i,j);
return out;
}

int main()
{
// called like :
Mat_<int> in;
Mat_<int> res = my_func(in);
return 0;
}

老实说,这是一种非常罕见的情况,您在编译时不知道 Mat 的类型,对于那些您仍然需要代码,如 if type==5 do_something,由 typeid 或类似索引的函数指针数组。

关于c++ - 如何在 opencv c++ 中为不同的 Matrix 类型编写方法而不明确指定 Mat 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21268869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com