chromium/third_party/mediapipe/src/mediapipe/calculators/core/matrix_subtract_calculator.cc

// Copyright 2019 The MediaPipe Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "Eigen/Core"
#include "mediapipe/framework/api2/node.h"
#include "mediapipe/framework/calculator_framework.h"
#include "mediapipe/framework/formats/matrix.h"
#include "mediapipe/framework/port/status.h"

namespace mediapipe {
namespace api2 {

// Subtract input matrix from the side input matrix and vice versa. The matrices
// must have the same dimension.
// Based on the tag (MINUEND vs SUBTRAHEND), the matrices in the input stream
// and input side packet can be either subtrahend or minuend. The output matrix
// is generated by performing minuend matrix - subtrahend matrix.
//
// Example config:
// node {
//   calculator: "MatrixSubtractCalculator"
//   input_stream: "MINUEND:input_matrix"
//   input_side_packet: "SUBTRAHEND:side_matrix"
//   output_stream: "output_matrix"
// }
//
// or
//
// node {
//   calculator: "MatrixSubtractCalculator"
//   input_stream: "SUBTRAHEND:input_matrix"
//   input_side_packet: "MINUEND:side_matrix"
//   output_stream: "output_matrix"
// }
class MatrixSubtractCalculator : public Node {
 public:
  static constexpr Input<Matrix>::SideFallback kMinuend{"MINUEND"};
  static constexpr Input<Matrix>::SideFallback kSubtrahend{"SUBTRAHEND"};
  static constexpr Output<Matrix> kOut{""};

  MEDIAPIPE_NODE_CONTRACT(kMinuend, kSubtrahend, kOut);
  static absl::Status UpdateContract(CalculatorContract* cc);

  absl::Status Process(CalculatorContext* cc) override;
};
MEDIAPIPE_REGISTER_NODE(MatrixSubtractCalculator);

// static
absl::Status MatrixSubtractCalculator::UpdateContract(CalculatorContract* cc) {
  // TODO: the next restriction could be relaxed.
  RET_CHECK(kMinuend(cc).IsStream() ^ kSubtrahend(cc).IsStream())
      << "MatrixSubtractCalculator only accepts exactly one input stream and "
         "one input side packet";
  return absl::OkStatus();
}

absl::Status MatrixSubtractCalculator::Process(CalculatorContext* cc) {
  const Matrix& minuend = *kMinuend(cc);
  const Matrix& subtrahend = *kSubtrahend(cc);
  if (minuend.rows() != subtrahend.rows() ||
      minuend.cols() != subtrahend.cols()) {
    return absl::InvalidArgumentError(
        "Minuend and subtrahend must have the same dimensions.");
  }
  kOut(cc).Send(minuend - subtrahend);
  return absl::OkStatus();
}

}  // namespace api2
}  // namespace mediapipe