我在C ++中使用Tensorflow。我正在使用训练有素的模型从输入图像中提取补丁。
我的输出张量(在会话运行之后)是outputs
,并且在outputs[0]
中有一批N个补丁MxMxD。
auto patches = outputs[0].tensor<float, 4>();
现在,我想使用OpenCV来显示这些图像,特别是我想使用cv::eigen2cv
函数,即给定Eigen::Matrix
给我一个cv::Mat
。
问题是我需要遍历此输出张量,并为每个元素提取一个Eigen::Matrix
。
我在这里尝试了建议的解决方案:https://stackoverflow.com/a/39475756/2891324,但是由于Eigen错误,我什至无法编译代码:EIGEN_STATIC_ASSERT_VECTOR_ONLY:
const auto patch_side = 256;
int batch_id = 0;
using Matrix =
Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
for (auto i = 0; i < grid_shape.second; ++i) {
for (auto j = 0; j < grid_shape.first; ++j) {
auto size = patch_side * patch_side * depth;
auto map =
Eigen::Map<Matrix>(patches.data() + batch_id * size, size);
// Eigen::Matrix4f m = map;
Matrix m = map;
cv::Mat p;
cv::eigen2cv(m, p);
cv::imshow("p", p);
cv::waitKey();
/*
ml(cv::Rect(i * patch_side, j * patch_side, patch_side,
patch_side)) =
cv::Mat(cv::Size(patch_side, patch_side), CV_32F, patches.slice
patches.data() + (i + j) * patch_side * patch_side);
*/
std::cout << "i,j" << i << "," << j << "\n";
batch_id++;
}
}
那么,如何从Eigen :: Tensor(或tf :: Tensor)中获得可以用于cv::eigen2cv
的矩阵?
答案 0 :(得分:1)
看看the documenation of OpenCV,并考虑TensorFlow张量始终是行主要的,您应该能够执行以下操作:
const auto patch_side = 256;
int batch_id = 0;
for (auto i = 0; i < grid_shape.second; ++i) {
for (auto j = 0; j < grid_shape.first; ++j) {
auto size = patch_side * patch_side * depth;
cv::Mat p(patch_side, patch_side, CV_32FC(depth), patches.data() + batch_id * size);
cv::imshow("p", p);
cv::waitKey();
/*
ml(cv::Rect(i * patch_side, j * patch_side, patch_side,
patch_side)) =
cv::Mat(cv::Size(patch_side, patch_side), CV_32F, patches.slice
patches.data() + (i + j) * patch_side * patch_side);
*/
std::cout << "i,j" << i << "," << j << "\n";
batch_id++;
}
}
请注意,这不会复制张量数据,而是创建指向其的cv::Mat
。