在 TensorFlow API 中使用批处理时,“参数无效:输出维度必须为正”

Mis*_*kyy 5 c++ tensorflow

对于视频中的对象检测,我们使用大小大于 1 的批次。但是在视频结束时,当剩余帧数少于批次大小时,我们会收到以下错误:

2018-06-07 15:31:26.456907: W tensorflow/core/framework/op_kernel.cc:1290] CtxFailure at image_resizer_state.h:84: Invalid argument: output dimensions must be positive
Run Code Online (Sandbox Code Playgroud)

为了读取视频,我们使用 Opencv 3.3.0,帧存储在向量中batch

for (size_t i = 0; i < batch_size; i++) {
  ret = cap.read(readImage);
  if (!ret) {
    break;
  }
  batch.push_back(readImage.clone());
}
Run Code Online (Sandbox Code Playgroud)

该向量被转换为 tf 张量为

tensorflow::Tensor inputImg(
    tensorflow::DT_UINT8,
    tensorflow::TensorShape(
        {static_cast<long long int>(batch.size()), height, width, depth}));
for (size_t i = 0; i < batch.size(); i++) {
  auto tmp = inputImg.Slice(i, i + 1);
  uint8_t *p = tmp.flat<uint8_t>().data();
  cv::Mat cameraImg(height, width, CV_8UC3, p);
  batch[i].convertTo(cameraImg, CV_8UC3);
}
Run Code Online (Sandbox Code Playgroud)

您可以注意到张量是根据实际批次的大小进行初始化的,因此它在开始时包含定义数量的图像,在视频结束时包含较少的图像。

之后我们运行“探测器”

  std::vector<tensorflow::Tensor> output_tensors;
  tensorflow::Status status =
      session->Run({{"image_tensor:0", inputImg}}, {"detection_boxes:0", "detection_scores:0",
                    "detection_classes:0", "num_detections:0"}, {}, &output_tensors);
Run Code Online (Sandbox Code Playgroud)

最终出现错误(status.ok() == False并显示提到的消息)。

因此,在整个视频中我们没有错误,但是当只剩下 2 个图像时(因此向量的batch大小为 2),但之前的批量大小为 5,我们就会出现错误并且output_tensors大小为 0。我们尝试运行我们的检测器每次迭代随机改变批量大小,并且当当前批量具有与前一个批量不同的大小时没有错误,它只发生在视频末尾。

如果我们选择批量大小使得

视频大小 % 批量大小 == 0

该错误也不会发生。

我们使用从源代码master分支)构建的 TF。

有谁知道这个问题的解决方案?