将std :: string转换回使用std :: stringstream<<生成的cv :: Mat CV ::垫

时间:2014-08-01 09:22:10

标签: c++ opencv stringstream mat

我正在为立体视觉保存校准数据,而不是以特殊数据格式从opencv获取给定的YAML数据结构,这使我更具灵活性。

因为我正在使用一点hack将cv :: Mat转换为std :: string:

cv::Mat mat;
// some code
std::stringstream sstrMat;
sstrMat << mat;
saveFoo(sstrMat.str()); // something like this to save the matrix

作为输出,我从sstrMat.str()变成了我需要的所有数据:

[2316.74172937253, 0, 418.0432610206069;
  0, 2316.74172937253, 253.5597342849773;
  0, 0, 1]

我的问题是反向操作:将此std :: string转换回cv :: Mat。

我尝试过这样的代码:

cv::Mat mat;
std::stringstream sstrStr;
sstrStr << getFoo() // something like this to get the saved matrix

sstrStr >> mat;  // idea-1: generate compile error
mat << sstrStr;  // idea-2: does also generate compile error

我的所有尝试都失败了,所以我会问你是否知道opencv的方法可以将该字符串转换回来,或者我是否编写了自己的方法来执行此操作。

1 个答案:

答案 0 :(得分:1)

您自己实施了operator<<(std::ostream&, const Mat&)吗?如果是这样的话,你显然也必须自己做反向操作,如果你愿意的话。

根据您的输出,我猜矩阵的类型为CV_64F,有3个通道。请务必记住矩阵的大小,然后查看documentation

您可以使用这些规范创建矩阵,并在读取流时填充值。互联网上有多个流阅读的例子,但在你的情况下,这很简单。忽略您不需要([ ] , ;std::istream::read的字符到虚拟缓冲区中,然后使用operator>>(std::istream&, double)来获取您的值。

很酷的是,您可以像在标准库容器上一样遍历cv::Mat。因此,如果您正在使用C ++ 11,它可能看起来像这样(未经测试):

int size[2] = {x, y}; // matrix cols and rows
cv::Mat mat(3, size, CV_F64); // 3-dimensional matrix

for(auto& elem : mat)
{
    cv::Vec3d new_elem; // a 3D vector with double values
    // read your 3 doubles into new_elem
    // ...

    elem = new_elem; // assign the new value to the matrix element
}

同样,我没有广泛使用OpenCV,所以请参阅文档以检查一切是否正确。

相关问题