mediapipe新增graph和caculator
在实际工作项目中,尤其是Camera、嵌入式AI领域,其软件架构大概率会用到pipeline。pipeline架构的核心是计算图的构建和计算节点的调度。本系列文章主要借mediapipe框架,学习pipeline模式的核心思想。
本文主要讲在mediapipe中如何新增一个自定义的graph和calculator。
一、新增calculator
前几周在RK3588上编译并跑通了mediapipe,因此以下讲如何新增一个caculator,该calculator(以下简称rga_calculator)使用RGA模块缩放图像到指定尺寸。
1.1 新增proto配置文件
新增mediapipe/calculators/image/rga_calculator.proto
文件,该文件主要是为了导出rga_calculator支持的配置,如缩放后的图像尺寸output_width、output_height等。文件内容如下:
syntax = "proto2";
package mediapipe;
import "mediapipe/framework/calculator.proto";
message RgaCalculatorOptions {
// Output dimensions. Set to 0 if they should be the same as the input.
optional int32 output_width = 1 [default = 0];
optional int32 output_height = 2 [default = 0];
// Interpolation method to use. Note that on CPU when LINEAR is specified,
// INTER_LINEAR is used for upscaling and INTER_AREA is used for downscaling.
enum InterpolationMode {
DEFAULT = 0;
LINEAR = 1;
NEAREST = 2;
}
// Mode DEFAULT will use LINEAR interpolation.
optional InterpolationMode interpolation_mode = 9;
}
在mediapipe/mediapipe/calculators/image/BUILD
文件中,新增如下内容
mediapipe_proto_library(
name = "rga_calculator_proto",
srcs = ["rga_calculator.proto"],
deps = [
"//mediapipe/framework:calculator_options_proto",
"//mediapipe/framework:calculator_proto",
],
)
在mediapipe/framework/tool/mediapipe_proto_allowlist.bzl
文件rewrite_target_list
中新增
"rga_calculator_proto",
添加完成后,后续编译时编译器会根据rga_calculator.proto
文件,在mediapipe/bazel-bin/mediapipe/calculators/image
目录下生成rga_calculator.pb.h
和rga_calculator.pb.c
文件。这样在c++代码中就可以使用在proto文件中定义的字段了。
1.2 calculator代码实现
代码实现上很简单,只要继承CalculatorBase
类,并重写GetContract
、Open
、Process
、Close
方法就行了。其中GetContract
、Open
、Close
函数只执行一次,分别负责输入输出数据格式检查、初始化、释放资源;而Process方法每一帧都会执行,因此这里写缩放的具体实现。
新增mediapipe/calculators/image/rga_calculator.cc
文件,内容如下:
#include "absl/status/status.h"
#include "mediapipe/calculators/image/rga_calculator.pb.h"
#include "mediapipe/framework/calculator_framework.h"
#include "mediapipe/framework/formats/image_frame.h"
#include "mediapipe/framework/formats/image_frame_opencv.h"
#include "mediapipe/framework/formats/video_stream_header.h"
#include "mediapipe/framework/packet.h"
#include "mediapipe/framework/port/opencv_core_inc.h"
#include "mediapipe/framework/port/opencv_imgproc_inc.h"
#include "mediapipe/framework/port/ret_check.h"
#include "mediapipe/framework/port/status.h"
#include "mediapipe/framework/timestamp.h"
#include "rga.h"
#include "RgaUtils.h"
#include "im2d.h"
typedef int DimensionsPacketType[2];
#define DEFAULT_SCALE_MODE mediapipe::ScaleMode_Mode_STRETCH
namespace mediapipe {
#if !MEDIAPIPE_DISABLE_GPU
#endif // !MEDIAPIPE_DISABLE_GPU
namespace {
constexpr char kImageFrameTag[] = "IMAGE";
} // namespace
class RgaCalculator : public CalculatorBase {
public:
RgaCalculator() = default;
~RgaCalculator() override = default;
static absl::Status GetContract(CalculatorContract* cc)