Home How to create cv::Mat from buffer (array of T* data) using a template function?
Reply: 1

How to create cv::Mat from buffer (array of T* data) using a template function?

ted930511 Published in 2018-01-11 13:06:14Z

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;

I am new to template programming, I am quite confused how to implement T-cv_types correspondence.

Anyone has any idea? Thank you!!!

Silencer Reply to 2018-01-11 13:17:29Z

Use cv::DataType<T>::type .

Here is an example.

//! 2018.01.11 21:16:32 CST
// Create Mat from buffer 
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;

template <typename T>
Mat createMat(T* data, int rows, int cols) {
    Mat mat(rows, cols, cv::DataType<T>::type);
    memcpy(mat.data, data, rows*cols*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:\n"<< mat1 <<endl;
    cout << "Mat2:\n"<< mat2 <<endl;


[1, 2;
 3, 4]
[1.1, 2.2;
 3.3, 4.4]
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.497571 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO