如何将 OpenCV Mat 传递到 C 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 的输入的张量?

原文由 lefty 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 377
1 个回答

它不是直接来自 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 heightdepth 通道。例如,具有 3 个通道的 128 宽 x 64 高图像将以 {1, 64, 128, 3} 的形状传递。批量大小仅在您需要在一次调用中传入多个图像时使用,对于简单的用途,您可以将其保留为 1。

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

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

input_tensor_mapped 对象是新创建张量中数据的接口,然后您可以将自己的数据复制到其中。在这里,我假设您已将 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 方面,但希望这有助于您入门。

原文由 Pete Warden 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题