c++ - 如何将 OpenCV Mat 传递到 C++ Tensorflow 图中?

标签 c++ opencv tensorflow

在 Tensorflow C++ 中,我可以使用将图像文件加载到图表中

tensorflow::Node* file_reader =  tensorflow::ops::ReadFile(tensorflow::ops::Const(IMAGE_FILE_NAME, b.opts()),b.opts().WithName(input_name));
tensorflow::Node* image_reader = tensorflow::ops::DecodePng(file_reader, b.opts().WithAttr("channels", 3).WithName("png_reader"));
tensorflow::Node* float_caster = tensorflow::ops::Cast(image_reader, tensorflow::DT_FLOAT, b.opts().WithName("float_caster"));
tensorflow::Node* dims_expander = tensorflow::ops::ExpandDims(float_caster, tensorflow::ops::Const(0, b.opts()), b.opts());
tensorflow::Node* resized = tensorflow::ops::ResizeBilinear(dims_expander, tensorflow::ops::Const({input_height, input_width},b.opts().WithName("size")),b.opts());

对于嵌入式应用程序,我想将 OpenCV Mat 传递到此图中。

如何将 Mat 转换为可用作 tensorflow::ops::Cast 或 tensorflow::ops::ExpandDims 输入的张量?

最佳答案

它不是直接来自 CvMat,但您可以在 TensorFlow Android 示例中看到如何从内存中数组初始化张量的示例: https://github.com/tensorflow/tensorflow/blob/0.6.0/tensorflow/examples/android/jni/tensorflow_jni.cc#L173

您将从创建一个新的 tensorflow::Tensor 对象开始,使用类似这样的内容(所有代码未经测试):

tensorflow::Tensor input_tensor(tensorflow::DT_FLOAT, tensorflow::TensorShape({1, height, width, depth}));

这将创建一个具有浮点值的张量对象,批量大小为 1,大小为 width x height , 和 depth channel 。例如,具有 3 个 channel 的 128 宽 x 64 高图像将以 {1, 64, 128, 3} 的形状传递。 .批量大小仅在您需要在一次调用中传入多个图像时使用,对于简单的用途,您可以将其保留为 1。

然后你会得到张量后面的底层数组,使用这样的行:

auto input_tensor_mapped = input_tensor.tensor<float, 4>();

input_tensor_mapped object 是新创建的张量中数据的接口(interface),然后您可以将自己的数据复制到其中。这里我假设你设置了 source_data作为指向源数据的指针,例如:

const float* source_data = some_structure.imageData;

然后您可以遍历数据并将其复制过来:

for (int y = 0; y < height; ++y) {
    const float* source_row = source_data + (y * width * depth);
    for (int x = 0; x < width; ++x) {
        const float* source_pixel = source_row + (x * depth);
        for (int c = 0; c < depth; ++c) {
           const float* source_value = source_pixel + c;
           input_tensor_mapped(0, y, x, c) = *source_value;
        }
    }
}

有明显的机会来优化这种幼稚的方法,我手头没有示例代码来展示如何处理获取源数据的 OpenCV 方面,但希望这有助于您入门。

关于c++ - 如何将 OpenCV Mat 传递到 C++ Tensorflow 图中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36044197/

相关文章:

c++ - 从 Visual Studio 2010 开始,取消引用集合上的迭代器时的 Const 引用

c - 我如何使用 Opencv SparseMatrix

Opencv 静态构建、jpeg、png、tiff 不是静态链接的?

python-3.x - 从张量中获取值的随机索引

c++ - 并发排除调整

c++ - 在 ANTLR4 的 Lexer 中切换流

c++ - 0x800a1421 HRESULT 是什么意思?

c++ - 如何合并 HSV channel

optimization - Tensorflow 的超参数调整

带有需要 2.7 的运算符的 Python 3.6 Airflow