我以一种特殊的数据格式保存立体视觉的校准数据,而不是opencv中给定的YAML数据结构,这让我有了更大的灵活性。
因此,我使用了一个小技巧将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的一个方法来将这个字符串转换回来,或者我是否写了我自己的方法来做这件事。
发布于 2014-08-01 18:02:39
您自己实现了operator<<(std::ostream&, const Mat&)吗?如果是这样,显然你也必须自己做相反的操作,如果你想要的话。
从您的输出中,我猜测矩阵的类型是具有3个通道的CV_64F。一定要记住矩阵的大小,并检查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,所以请参考文档来检查一切都是正确的。
https://stackoverflow.com/questions/25076934
复制相似问题