convert armadillo data to other types of data

本文介绍如何在Armadillo C++线性代数库与STL、OpenCV等库之间进行数据格式转换。具体包括从Armadillo转换到STL的二维向量,以及Armadillo与OpenCV之间的矩阵数据互转方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

armadillo to other data format conversion

Armadillo is a C++ linear algebra library, especially for computer vision application.

Armadillo is more similar to MATLAB with decent performance. (check http://nghiaho.com/?p=1726 for comparison).

We may want to cooperate Armadillo with OpenCV, STL or FFTW. In this blog the conversion between STL and OpenCV will be described.

1. armadillo to STL vector

int nRow = 4;
int nCol = 5;
arma::mat A = arma::randu<arma::mat>(nRow, nCol);
std::cout << " arma::mat A: " << A << std::endl;
arma::mat tmpA = A.t();
 
std::vector< std::vector<double> > Vec;
Vec.resize(nRow);
     
for (int i = 0; i < nRow; i++) {
    // initialize tmpVec by input A data pointer
    std::vector<double> tmpVec( tmpA.colptr(i), tmpA.colptr(i) + nCol);
    Vec[i] = tmpVec;
}
 
std::cout << " A to tmpA conversion: " << std::endl;
BOOST_FOREACH(std::vector<double> tmpVec, Vec){
    BOOST_FOREACH(double d, tmpVec){
        std::cout << d << " ";
    }
    std::cout << std::endl;
}
}

2. Armadillo to OpenCV, Since OpenCV data is saved in row-wised, and armadillo data is saved in column-wised, therefore, when we convert the data, we may need to do transformation at first. The following is the sample code.

// -----------------------------
// arma::mat to opencv
// -----------------------------
cv::Mat img(2, 2, CV_32FC1);
cv::randu(img, cv::Scalar(0), cv::Scalar(255));
     
std::cout << "img Test" << img << std::endl;
cv::Mat imgt(img.t());
     
// mat to armadillo
arma::fmat armaConv(imgt.ptr<float>(), 2, 2);
std::cout << "armaConv" << std::endl << armaConv << std::endl;
}

3. OpenCV to Armadillo

// armadillo to mat
arma::fmat arma2matData = arma::randu<arma::fmat>(5, 6);
std::cout << "arma2matData: " << std::endl << arma2matData << std::endl;
     
cv::Mat cvMatConvTmp(6, 5, CV_32FC1, arma2matData.memptr());
cv::Mat cvMatConv(cvMatConvTmp.t());
std::cout << "cvMatConv: " << std::endl << cvMatConv << std::endl;
}
4. STL 2D vector (vector<vector<T> >) to Opencv cv::Mat 2D matrix

template <typename T>
cv::Mat_<t> vec2cvMat_2D(std::vector< std::vector<T> > &inVec){
  int rows = static_cast<int>(inVec.size());
 int cols = static_cast<int>(inVec[0].size());
  
 cv::Mat_<t> resmat(rows, cols);
 for (int i = 0; i < rows; i++)
 {
  resmat.row(i) = cv::Mat(inVec[i]).t();
 }
 return resmat;
}
origin blog address:http://dragonwood-blastevil.blogspot.com/2013/04/armadillo-to-other-data-format.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值