我想编写一个模板函数来将指针T* image
引用的数据复制到cv::Mat
.我很困惑如何概括 T 和 cv_type 匹配.
I'd like to write a template function to copy data referenced by pointer T* image
to cv::Mat
. I am confusing how to generalize T and cv_type matching.
template<typename T>
cv::Mat convert_mat(T *image, int rows, int cols) {
// Here we need to match T to cv_types like CV_32F, CV_8U and etc.
// The key point is how to connect these two
cv::Mat mat(rows, cols, cv_types, image);
return mat;
}
我是模板编程的新手,我很困惑如何实现T-cv_types对应.
I am new to template programming, I am quite confused how to implement T-cv_types correspondence.
有人知道吗?谢谢!!!
Anyone has any idea? Thank you!!!
使用 cv::DataType
.
这是一个例子.
// Create Mat from buffer
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
/*
//! First version
//! 2018.01.11 21:16:32 (+0800)
template <typename T>
Mat createMat(T* data, int rows, int cols) {
// Create Mat from buffer
Mat mat(rows, cols, cv::DataType<T>::type);
memcpy(mat.data, data, rows*cols * sizeof(T));
return mat;
}
*/
//! Second version
//! 2018.09.03 16:00:01 (+0800)
template <typename T>
cv::Mat createMat(T* data, int rows, int cols, int chs = 1) {
// Create Mat from buffer
cv::Mat mat(rows, cols, CV_MAKETYPE(cv::DataType<T>::type, chs));
memcpy(mat.data, data, rows*cols*chs * sizeof(T));
return mat;
}
int main(){
int arr1[4] = {1,2,3,4};
double arr2[4] = {1.1,2.2,3.3,4.4};
Mat mat1 = createMat<int>(arr1, 2,2);
Mat mat2 = createMat<double>(arr2, 2,2);
cout << "Mat1:
"<< mat1 <<endl;
cout << "Mat2:
"<< mat2 <<endl;
}
结果:
Mat1:
[1, 2;
3, 4]
Mat2:
[1.1, 2.2;
3.3, 4.4]
这篇关于如何使用模板函数从缓冲区(T* 数据数组)创建 cv::Mat?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!