Use cv::DataType<T>::type
.
Here is an example.
// 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;
}
Result:
Mat1:
[1, 2;
3, 4]
Mat2:
[1.1, 2.2;
3.3, 4.4]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…